简体   繁体   English

其他进程正在使用的C#文件

[英]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. 当我运行它时,它指向File.Create(Path.Combine("logs", _logFile)).Close()行,并给我错误。

Edit: I changed if(!File.Exists(_logFile)) to if(!File.Exists(Path.Combine("logs", _logFile))) but I still get the same error. 编辑:我将if(!File.Exists(_logFile))更改为if(!File.Exists(Path.Combine("logs", _logFile)))但仍然遇到相同的错误。

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. 这样,无论using块内部发生什么情况,您都知道该文件将被关闭,因此您以后可以再次使用它。

Note that File.AppendText will create the file if it doesn't already exist, so File.Create is not needed. 需要注意的是File.AppendText将创建文件,如果它不存在,所以File.Create是没有必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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