尽管锁定了块,但写入文本文件时出现 IOException
我知道答案一定就在某个地方,我应用了许多其他问题和 MSDN 本身的建议,但我可能在这里忽略了一些东西。
这是我的方法,我用它将输出转储到文件。为了清楚起见,附加了锁定对象声明。
private static Object fileLock = new Object();
private static void WriteToFile(string msg, bool WriteLine)
{
lock (fileLock)
{
msg = DateTime.Now.ToShortTimeString() + " - " + msg;
FileInfo F = new FileInfo("dump.txt");
using (StreamWriter writer = F.Exists ? F.AppendText() : F.CreateText()) //<--THIS LINE THROWS
{
if (WriteLine)
writer.WriteLine(msg);
else
writer.Write(msg);
}
}
}
问题是:为什么上面的 using
行会在我第二次调用该方法时抛出 IOException
抱怨另一个进程正在使用该文件?
我在我的代码中这样称呼它:
Console.WriteLine(something)
#if(DEBUG)
Extensions.WriteToFile(something,true);
#endif
再次,我确定这是一个微不足道的问题,其他人问了类似的问题得到了正确的答案,但我无法挖掘它。
更新
重构FileInfo
对象并切换到File.XXX
方法使代码工作正常。我仍然想知道问题是什么,无论如何问题看起来已经解决了。
I know the answer must be out there somewhere, I applied suggestions both from many other questions and from MSDN itself but I'm probably overlooking something here.
This is my method, I use it to dump output to file. lock object declaration attached for clarity.
private static Object fileLock = new Object();
private static void WriteToFile(string msg, bool WriteLine)
{
lock (fileLock)
{
msg = DateTime.Now.ToShortTimeString() + " - " + msg;
FileInfo F = new FileInfo("dump.txt");
using (StreamWriter writer = F.Exists ? F.AppendText() : F.CreateText()) //<--THIS LINE THROWS
{
if (WriteLine)
writer.WriteLine(msg);
else
writer.Write(msg);
}
}
}
Question is: Why does the using
line above throws an IOException
complaining another process is using the file the 2nd time I call the method ?
I'm calling it like this around my code:
Console.WriteLine(something)
#if(DEBUG)
Extensions.WriteToFile(something,true);
#endif
Again, I'm sure this is a trivial issue and someone else asked something like this getting the right answer, but I'm unable to dig it up.
UPDATE
Refactoring out the FileInfo
object and switching to File.XXX
methods made the code work fine. I still wonder what the issue was, anyway the issue looks like solved.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@Guffa:声明必须是私有静态对象 fileLock = new object();
@alex:你的代码在我的机器上运行得很好,尽管在我看来,它对于任务来说有点太复杂了。
也许某些防病毒软件或索引器会锁定您的转储文件。
@Guffa: declaration has to be private static object fileLock = new object();
@alex: Your code works just fine on my machine although it's a bit too complicated for the task imo.
Maybe some antivirus or indexer locks your dump file.