OK, if you think Jon Box is smart, please do not read the rest of this.
Today, I had a Windows Service started throwing an error on the opening of a text file after months of working nicely. After some investigation, I found a couple of issues that brought this to be. First, another vendor’s application which creates the files installed an upgrade today and this new version keeps the file open all of the time (well, for today anyway, which is when I want to read it). That’s cool – we should be able to handle that. Here is my code that was opening the file in Read only mode:
fs = New FileStream("\\yada\yada.txt", FileMode.Open, FileAccess.Read)
What’s wrong with it? Why would it throw an error for a file that is reportedly not locked by the other system?
So, after looking at the FileStream constructor documentation, there is a fourth parameter called share that is of type FileShare. This is an enumeration that contains constants for controlling the kind of access other FileStreams can have to the same file. The keyword here is “other”. This is obviously an important thing to communicate to the file system but I somehow assumed this was the default activity with the FileAccess set to Read. Now, it looks like:
fs = New FileStream("\\yada\yada.txt", FileMode.Open, _
FileAccess.Read, FileShare.ReadWrite)
Problem solved (after a little embarrassment).