简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM