簡體   English   中英

C#進程無法訪問文件“ XYZ”,因為它正在被另一個進程使用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM