This is all to do with the lock and sharing semantics that you request when opening the file.
Instead of using the shortcut approach of File.ReadAllText()
, try looking into using a System.IO.FileStream
and a System.IO.StreamReader
/ System.IO.StreamWriter
.
To open a file:
using (var fileStream = new FileStream(@"c:\myFile", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var streamReader = new StreamReader(fileStream))
{
var someText = streamReader.ReadToEnd();
}
Note the FileShare.ReadWrite
- this is telling the stream to allow sharing to either other readers or other writers.
For writing try something like
using (var fileStream = new FileStream(@"c:\myFile", FileMode.Create, FileAccess.Write, FileShare.Read))
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.WriteLine("some text");
}
Note the FileShare.Read
- this is telling the stream to allow sharing to readers only.
Have a read around the System.IO.FileStream
and its constructor overloads and you can tailor exactly how it behaves to suit your purpose.