Sharing an open file between processes

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
 
V

Vijaye Raji

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top