2016-08-12 42 views
0

讓我有打開文件並追加內容的程序。 如果我應該運行兩個apllication,我會得到另一個進程使用的IOException文件。如何檢查Log.txt文件正在被另一個進程使用?進程使用的C#檢查文件

class Program 
{ 
    static void Main(string[] args) 
    { 
     FileInfo file = new FileInfo(@"D:\Log.txt"); 
     using (StreamWriter sw = file.AppendText()) 
     { 
      for (int i = 0; i < 1000; i++) 
      { 
       System.Threading.Thread.Sleep(100); 
       sw.WriteLine("Hello"); 
       sw.WriteLine("And"); 
       sw.WriteLine("Welcome"); 
      } 
      Console.WriteLine("The work is done"); 
     } 
    } 
} 
+0

是否要檢查_if_文件是否被另一個進程使用,或者您想檢查_what_進程是否正在使用它? –

+0

@VisualVincent,我想檢查一下情況。 – A191919

+0

然後Try/Catch是您的解決方案。薩姆提供了一個很好的答案。 –

回答

3

您應該嘗試打開並寫入文件。如果它正在使用中,你會得到一個異常。在.NET中沒有其他方式。

protected virtual bool IsFileLocked(FileInfo file) 
{ 
    FileStream stream = null; 

    try 
    { 
     stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None); 
    } 
    catch (IOException) 
    { 
     //the file is unavailable because it is: 
     //still being written to 
     //or being processed by another thread 
     //or does not exist (has already been processed) 
     return true; 
    } 
    finally 
    { 
     if (stream != null) 
      stream.Close(); 
    } 

    //file is not locked 
    return false; 
} 
+0

這是正確的:當某些進程可以從文件中讀/寫時,任何可能的測試和實際寫入文件之間存在*時間差*。 –

+1

如果你打算使用別人的答案它的好形式包括一個鏈接到他們的帖子http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-正在使用 – MikeT

+0

@MikeT答案是我的,我提供的代碼已被用於其他答案的事實是無關緊要的,因爲如果您在stackoverflow或谷歌搜索,你會發現在1000年的文章中使用完全相同的代碼。 ..那麼,誰是主人?您提供的鏈接是否是從某處複製的其他用戶?無果而無意義的辯論,對不起。 – sam

相關問題