【发布时间】:2015-09-23 21:13:23
【问题描述】:
我正在尝试编写一个日志文件,但它不断显示“文件正在被另一个进程使用”。这是我的代码:
//_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));
}
当我运行它时,它指向File.Create(Path.Combine("logs", _logFile)).Close() 行并给我错误。
编辑:
我将if(!File.Exists(_logFile)) 更改为if(!File.Exists(Path.Combine("logs", _logFile))),但我仍然遇到同样的错误。
【问题讨论】:
-
你不需要
File.Create你创建一个文件并且永远不会用这段代码关闭它... -
您的
File.Exists没有检查与您在其上创建文件的路径相同的路径..._logFilevsPath.Combine("logs", _logFile) -
这可能很愚蠢,但是您是否在其他程序(例如记事本)中打开了相关文件?
-
Path.Combine("logs", _logFile)一遍又一遍是怎么回事 - 第一次不相信? -
所以它回到我之前的问题......你在哪里处理/关闭它?这段代码执行了多少次?如果您单步执行代码,是在第一次调用期间还是在第一次调用之后发生?
标签: c# streamwriter