How to avoid FileAccess exceptions when writing to a shared file?

R

Roger Helliwell

My web app writes all error/diagnostic messages to an error file in
Xml format. It seemed to be working fine, until I wrote a Windows app
that listens for changes in this file. If the file changes, the file
is loaded and displayed in a form for the administrator to review.

Now it seems there are (occasionally) times when the web-app fails
while trying to write to the file. Presumably this is due to the fact
that the Windows app is currently loading the file. I'm using
XmlDocument.Load() for this.

For now, I've wrapped my 'append an error' code in a loop which
repeatedly tries again if a FileAccess exception is caught. But there
must be a safer way to accomplish this.

Is there any mechanism in .NET that allows an exclusive lock on file?
Preferably one that causes any write request to wait until the lock is
released?

Thanks,
Roger
 
T

Tim_Mac

if you can centralise the access to the file, i.e. if the windows
application could open the file via a web service or something, then
you could hold the filestream object in application state, and use a
lock statement around accessing it, whether from web service, or your
error logging code on the web site. it shouldn't delay your app at all
as long as you only do file IO and no big processing jobs in the middle
of the statement.

is the windows application opening the file explicitly for reading
only? this might help with the locking situation. there are extra
parameters in the File.Open method which specify this. e.g.
File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None
)

hth
tim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top