简体   繁体   中英

Writing text to file from multiple instances of program

When I write info to file and multiple copies of program are runnnig I get this error:

The process cannot access the file 'C:\\logs\\log.txt' because it is being used by another process.

code is:

// create a writer and open the file
TextWriter tw2 = File.AppendText(@"C:\logs\log.txt");

// write a line of text to the file
tw2.WriteLine(Environment.NewLine);
tw2.WriteLine(DateTime.Now + " " + "IN INFOSERVCALLER");
tw2.Flush();

How to do it in right way?

Always encapsulate this kind of code in a using statement

using(TextWriter tw2 = File.AppendText(@"C:\logs\log.txt"))
{
    tw2.WriteLine(Environment.NewLine); 
    tw2.WriteLine(DateTime.Now + " " + "IN INFOSERVCALLER"); 
    //tw2.Flush();  // No need to flush because close alway flush.
}

The using statement calls tw2.Close() at the end of the block.
Also if you get exceptions while inside the block.

Now if the other instances of your application fails for some reason, the file is no more locked

Use Mutex class to synchronize access to log file from multiple processes. Call WaitOne before you open the file and call ReleaseMutex after you close the file (Flush is not enough, you must Close file or wrap it in using keyword, as other answers mentioned) when writing is done. Mutex name should start with prefix "Global\\".

Apart from Flushing, you have to Close() the file.

Besides, if another instance is writing the file at the same time, you can't access it (until the other program calls Close() .

TextWriter.Close Method

Closes the current instance of writer and releases any system resources associated with the writer

In this case the "system resource" refers to the file that keeps locked until you close it.

You need to close each time you open file with text writer.

So after each operation use

// create a writer and open the file
TextWriter tw2 = File.AppendText(@"C:\logs\log.txt");

// write a line of text to the file
tw2.WriteLine(Environment.NewLine);
tw2.WriteLine(DateTime.Now + " " + "IN INFOSERVCALLER");
tw2.Flush();
tw2.Close(); 

After that again try to write on that will not create any problem further.

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