HaemEternal
HaemEternal

Reputation: 2269

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.

Upvotes: 4

Views: 15651

Answers (3)

martavoi
martavoi

Reputation: 7092

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.

Upvotes: 8

Simon Whitehead
Simon Whitehead

Reputation: 65079

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

Upvotes: 2

Ravi Vanapalli
Ravi Vanapalli

Reputation: 9942

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

Upvotes: 0

Related Questions