I wanted to scan the contents of log files, but many of them failed to open because of:
The process cannot access the file 'filename' because it is being used by another process.
This is a pretty pedestrian error that most people will see in their lives and probably accept and ignore. I was less happy though because I could open the files in Notepad but my simple use of new StreamReader(filename) was failing. I guessed there would be some combination of classes and parameters that would let me read the files, and after trying several combinations I found this works:
using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(stream))
{
string line = reader.ReadLine();
}
The FileShare values are described in the Win32 CreateFile documentation. The values are published unchanged as a .NET enum.
You are still at the mercy of how the other process has opened the file you are trying to read. You can open a file so that it is deliberately inaccessible to others.
No comments:
Post a Comment