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
usingstatementThe
usingstatement 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