Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamWriter/StreamReader File In Use By Another Process

I have a StreamWriter object to write to a log file, it is initialised as follows:

StreamWriter streamWriter = File.AppendText(GetLogFilePath());
streamWriter.AutoFlush = true;

Later in my code, I need to close the log file, and then read in part of the logged out contents. I have the following code:

streamWriter.Close();
streamWriter = null;
StreamReader logFileStream = File.OpenText(GetLogFilePath());

This is throwing an exception: The process cannot access the file because it is being used by another process.

Presumably, the problem is that the log file is not correctly closed when I close the StreamWriter.

Is there a better way to close a StreamWriter to ensure that the file it has open, is correctly closed?

UPDATE: I have resolved my issue. It was caused by an unrelated problem (where a separate application was accessing the file that I was trying to access). I am accepting Dmitry Martovoi's answer, as I think it is the most useful for other people who have a similar issue in the future; but an important note is that the solution does require the log file to be opened every time the log is written to, which can cause unnecessary overhead.

like image 700
HaemEternal Avatar asked Dec 26 '22 11:12

HaemEternal


1 Answers

I always wrap such code in a using statement

using (StreamWriter writer = File.AppendText(path)) 
{
   writer.WriteLine("This");
   writer.WriteLine("is Extra");
   writer.WriteLine("Text");
}

but for StreamWriter Close method doing exactly the same as Dispose.

like image 134
Dzmitry Martavoi Avatar answered Jan 15 '23 12:01

Dzmitry Martavoi