StreamWriter/StreamReader File In Use By Another Process

14,590

Solution 1

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.

Solution 2

You should wrap each file operation in a using block:

using (StreamWriter s = new StreamWriter(/* your arguments here *\)) {
    // code that uses it here
}
// file is closed here
Share:
14,590
HaemEternal
Author by

HaemEternal

Updated on June 18, 2022

Comments

  • HaemEternal
    HaemEternal almost 2 years

    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.