lock file access

  • Thread starter Thread starter Colin
  • Start date Start date
C

Colin

I'm using system.io.file How do I lock access to the file while appending?
Other processes may try to open it while I want it.

Thanks,
Colin.
 
Hi Colin,

By default, if you open a file for writting, it is locked and not
others cannot write to the same file until you close it. It you also
don't want others to read, you could pass FileShare.None to the
constructor of FileStream.

FileStream stream = new FileStream(name, FileMode.Append,
FileAccess.Write, FileShare.None);
StreamWriter w = new StreamWriter(stream);

Regards,
Thi - http://thith.blogspot.com
 
I understand my problem better now. When another process has a lock on the
file, I would like to wait until the lock is released and then do my append.
How can I do this?

Thanks,
Colin.


Hi Colin,

By default, if you open a file for writting, it is locked and not
others cannot write to the same file until you close it. It you also
don't want others to read, you could pass FileShare.None to the
constructor of FileStream.

FileStream stream = new FileStream(name, FileMode.Append,
FileAccess.Write, FileShare.None);
StreamWriter w = new StreamWriter(stream);

Regards,
Thi - http://thith.blogspot.com
 
Hi Colin, the way I often do is waiting for some time (Thread.Sleep)
and try again, may need to try several time.

Hope it helps,
Thi
 

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

Back
Top