[英]C# The process cannot access file 'XYZ' because it is being used by another process
最近几天,我一直在与这个问题作斗争,当我在开发机器上时,它可以正常工作,但是在客户端上却显示此错误。
现在,这是我所拥有的代码,似乎正在显示错误,因此任何帮助或指导都将是惊人的,在此先感谢您。
private void document()
{
StreamWriter sWrite = new StreamWriter("C:\\Demo\\index.html");
//LOTS OF SWRITE LINES HERE
sWrite.Close();
System.Diagnostics.Process.Start("C:\\Demo\\index.html");
}
因此,我不知道如果我两次运行此方法,它会一直告诉我该文件已被另一个进程使用。
例如,在尝试从Process.Start打开文件之前,您可以执行以下操作
var path = @"C:\Demo\index.html";
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine("Your contents to be written go here");
}
System.Diagnostics.Process.Start(path);
其中一些取决于确切的行为。 这可能有几个原因:例如,可能是由于异常。 以下代码将产生您描述的异常。
for (int i = 0; i < 10; i++)
{
const string path = @"[path].xml";
try
{
// After the first exception, this call will start throwing
// an exception to the effect that the file is in use
StreamWriter sWrite = new StreamWriter(path, true);
// The first time I run this exception will be raised
throw new Exception();
// Close will never get called and now I'll get an exception saying that the file is still in use
// when I try to open it again. That's because the file lock was never released due to the exception
sWrite.Close();
}
catch (Exception e)
{
}
//LOTS OF SWRITE LINES HERE
Process.Start(path);
}
“正在使用”块将解决此问题,因为它等效于:
try
{
//...
}
finally
{
stream.Dispose();
}
在你的代码的情况下,如果你做一大堆的线写它实际上没有任何意义考虑,如果(当)你想在某个时候调用Flush。 问题是写入应该是“全部还是全部”-即,如果发生异常,您是否仍要写入前几行? 如果没有,只需使用“ using”块-它会在“ Dispose”的末尾调用“ Flush”一次。 否则,您可以更早地调用“冲洗”。 例如:
using (StreamWriter sw = new StreamWriter(...))
{
sw.WriteLine("your content");
// A bunch of writes
// Commit everything we've written so far to disc
// ONLY do this if you could stop writing at this point and have the file be in a valid state.
sw.Flush();
sw.WriteLine("more content");
// More writes
} // Now the using calls Dispose(), which calls Flush() again
一个可能的大错误是,如果您在多个线程上执行此操作(尤其是如果您执行大量写操作)。 如果一个线程调用您的方法并开始写入文件,然后另一个线程也调用该方法并尝试也开始写入文件,则第二个线程的调用将失败,因为第一个线程仍在使用文件。 在这种情况下,您将需要使用某种锁定方式,以确保线程“轮流”写入文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.