kjsmita6
kjsmita6

Reputation: 464

C# File being used by another process

I am trying to write a log file, but it constantly says "File being used by another process". Here's my code:

//_logFile = "system.log"
if(!File.Exists(Path.Combine("logs", _logFile)))
        {
            File.Create(Path.Combine("logs", _logFile)).Close();
            sw = File.AppendText(Path.Combine("logs", _logFile));
        }
        else
        {
            sw = File.AppendText(Path.Combine("logs", _logFile));
        }         

When I run it, it points to the File.Create(Path.Combine("logs", _logFile)).Close() line and gives me the error.

Edit: I changed if(!File.Exists(_logFile)) to if(!File.Exists(Path.Combine("logs", _logFile))) but I still get the same error.

Upvotes: 0

Views: 2582

Answers (1)

Nathan A
Nathan A

Reputation: 11319

Assuming you don't need access to this stream outside the context of this method, I'd refactor your code to this:

var filePath = Path.Combine("logs", _logFile);

using (var sw = File.AppendText(filePath))
{
    //Do whatever writing to stream I want.
    sw.WriteLine(DateTime.Now.ToString() + ": test log entry");
}

This way, no matter what happens inside the using block, you know the file will be closed so you can use it again later.

Note that File.AppendText will create the file if it doesn't already exist, so File.Create is not needed.

Upvotes: 3

Related Questions