Locked Out of My File!
Too many applications hold file locks unnecessarily by design. Nonetheless, for many purposes I often want to read those files and assume I'll be "lucky" and not get inconsistent data. Or perhaps I want to read some data (e.g. a magic cookie header to test format) that I know won't change even if the file is being written. For some reason the way to open a .NET FileStream for reading a locked file has always eluded me. If you want to read a file and are getting the following error
Unhandled Exception: System.IO.IOException: The process cannot
access the file 'blah.txt' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access,
Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize,
FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
...
You just need to indicate explicitly that you're willing to share your file handle. In other words, you're feeling lucky, punk.
using (FileStream fs = new FileStream(@"blah.txt", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite))
Console.Out.WriteLine(fs.ReadByte());
The FileShare.ReadWrite indicates you're willing to share this file with people who are reading and writing to it. Once you think about it that way, it's obvious. For some reason, I kept looking for flags that indicated how little I wanted to touch the file, and this flag didn't jump out at me.

0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home