Sharing an open file between processes

  • Thread starter Thread starter Doug Wyatt
  • Start date Start date
D

Doug Wyatt

So I have a log file that I'm writing with one C# program and want to open
and read it in another one. I open it via :

StreamWriter log = File.AppendText(logPath);
log.AutoFlush = true;

but when I try to read it with another application, for instance, like :
StreamReader log = new StreamReader(logPath);
String logContents = log.ReadToEnd();
log.Close();

it fails complaining about it already being open by another application. Is
it possible to share a file between two processes such that one can be
writing to it and another can read from it? I'm not too concerned about
race conditions (like what happens if the reader catches the writer in the
middle of writing a buffer).

Thanks,
Doug Wyatt
 
You can share a file by setting the proper Share flags.

In the read-app, use,

File.Open(logPath, FileMode.Append, FileAccess.Write, FileShare.Read);

In the write-app, use,

File.Open(logPath, FileMode.Open, FileAccess.Read, FileShare.Write);

vJ
 
Back
Top