4

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.

HaemEternal
  • 2,229
  • 6
  • 31
  • 50

3 Answers3

8

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.

HaemEternal
  • 2,229
  • 6
  • 31
  • 50
Dzmitry Martavoi
  • 6,867
  • 6
  • 38
  • 59
  • The trouble with that is, the file has to be opened every time that you write to the log. In my case, this was taking up too much time. – HaemEternal Jan 22 '13 at 13:01
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
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • The trouble with that is, the file has to be opened every time that you write to the log. In my case, this was taking up too much time. – HaemEternal Jan 22 '13 at 13:01
0

Try using File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None);

Ravi Vanapalli
  • 9,805
  • 3
  • 33
  • 43