C#进程无法访问文件'XYZ',因为它正由另一个进程使用

时间:2016-08-17 18:25:02

标签: c# html streamwriter process.start

我在最近几天一直在与这个问题作斗争,当我在我的开发机器上时,它工作正常,但在客户端它显示此错误。

现在这是我的代码,似乎显示错误,所以任何帮助或指导都会很惊人,谢谢你提前。

 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");
 }

所以我不知道它一直告诉我,如果我运行这个方法两次,文件已经被另一个进程使用了​​。

2 个答案:

答案 0 :(得分:2)

这是您在尝试从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);

答案 1 :(得分:2)

其中一些取决于确切的行为。这可能有几个原因:例如,可能是由于例外。以下代码将生成您所描述的异常。

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。问题是写入应该是“全部还是全部” - 即如果发生异常,您是否仍希望仍然写入前面的行?如果没有,只需使用“使用”块 - 它将在“Dispose”结束时调用“Flush”一次。否则,您可以提前调用“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

一个很大的错误就是如果你在多个线程上执行此操作(特别是如果你正在进行大量写操作)。如果一个线程调用您的方法并开始写入该文件,然后另一个线程也调用它并尝试开始写入该文件,则第二个线程的调用将失败,因为第一个线程仍在使用该文件。如果是这种情况,你需要使用某种锁来确保线程“轮流”写入文件。