2010-12-12 47 views
0
public static void WriteLine(string text) 
    { 
     StreamWriter log; 

     if (!File.Exists(Filename)) 
     { 
      log = new StreamWriter(Filename); 
     } 
     else 
     { 
      log = File.AppendText(Filename); 
     } 

while this method is processed,other process also call this method。 「文件已被其他進程訪問」會發生錯誤。如何通過等待先前的過程完成來解決這個問題。c#如果該文件被其他進程處理,如何訪問文件?

回答

1

這兩個進程都需要創建一個FileStream,它們指定了一個FileShare模式的寫入。然後,您也可以放棄測試文件是否存在,並使用Append FileMode。

2

我想操作系統想等到文件句柄可以自由使用然後寫入文件。在這種情況下,您應該嘗試獲取文件句柄,捕獲異常,並且如果異常是因爲該文件被另一個進程訪問,那麼請稍等片刻,然後重試。

public static void WriteLine(string text) 
     { 
      bool success = false; 
      while (!success) 
      { 

       try 
       { 
        using (var fs = new FileStream(Filename, FileMode.Append)) 
        { 
         // todo: write to stream here 

         success = true; 
        } 
       } 
       catch (IOException) 
       { 
        int errno = Marshal.GetLastWin32Error(); 
        if(errno != 32) // ERROR_SHARING_VIOLATION 
        { 
         // we only want to handle the 
         // "The process cannot access the file because it is being used by another process" 
         // exception and try again, all other exceptions should not be caught here 
         throw; 
        } 

       Thread.Sleep(100); 
       } 
      } 

     } 
+1

如果您的進程是唯一訪問該文件的進程,那麼您也可以使用鎖定。但是使用上面的代碼會更節省,因爲它甚至可以處理多個進程的文件訪問。 – flayn 2010-12-12 11:19:41

相關問題