简体   繁体   中英

FileStream/StreamWriter if another user has the file open

I am writing data to a log file as users submit information. Other users within the office may need to view this log file but I cannot continue writing to the log file as more inforation is submitted if the office user has the file open. Is there a way to continue writing to a file even if another user has an instance of the file open?

using(StreamWriter writer = new StreamWriter(@"\\filelocation\filename.csv"))
{
     writer.WriteLine("Testing, testing");

     writer.Close();
}

Might I suggest using the Trace if you need to continue creating a log file? You can attach a "listener" to the Trace like this.

Trace.Listeners.Add(new TextWriterTraceListener("myfilename.txt"));

Of course if you pass it a filename, it will not autoflush, and nothing will be in the file till it closes, or the buffer fills up. So you could create the stream at the start of your program.

FileInfo fi = new FileInfo("myLogFile.txt");
StreamWriter _sw;

void Main()
{
    _sw = fi.CreateText();
    _sw.AutoFlush = true;
    Trace.Listeners.Add(new TextWriterTraceListener(sw));
}

void Close()
{
    if(_sw != null)
    {
        _sw.Flush();
        _sw.Dispose();
    }
}

Then in your program, instead of opening and closing a file for each write to a "log" you can instead just do this.

Trace.WriteLine("My message here");

Trace has a cool thing called categories too, which are great for logs...

Trace.WriteLine("My message here", "INFO");

//Output:
//INFO: My message here

One thing I have found is that on some systems you cannot open the text file, but you can make a copy of it to open, and the original file will continue to fill.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM