So far I've tried everything with no success.
What I try to accomplish is, I want to open and lock a file for a certain time. Right after I've opened and locked the file, I try to open the same file just for reading purpose.
string filePath = "test.ini";
// Open and lock the file
FileStream configurationFile = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
configurationFile.Lock(1, configurationFile.Length);
// Open the same file just to read it
using (FileStream bufferStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(bufferStream))
{
string line;
while ((line = sr.ReadLine()) != null) // <--- Here I get the error
{
CustomMessageBox.Show(line);
}
}
}
I actually can open the file with FileStream and StreamReader but when it comes to use the StreamReader with for example sr.ReadLine() it throws an exception, that the file is in use by another process.
As it's mentioned here Reading a file used by another process [duplicate] the FileShare attribute should be ReadWrite but this didn't help.
Also I've tried all available encodings like StreamReader(bufferStream, Encoding.*)
but that didn't work either.
Is there something simple I'm overlooking?