2010-02-26 72 views

回答

4

嘗試打開與標誌「寫作」。如果失敗,該文件被其他進程「取走」。

FileStream fileStream = null; 

try 
{ 
    fileStream = 
     new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write); 
} 
catch (UnauthorizedAccessException e) 
{ 
    // The access requested is not permitted by the operating system 
    // for the specified path, such as when access is Write or ReadWrite 
    // and the file or directory is set for read-only access. 
} 
finally 
{ 
    if (fileStream != null) 
     fileStream.Close(); 
} 

P.S.剛剛發現基本一致的回答非常類似的問題:

C#: Is there a way to check if a file is in use?

+1

所以您可以通過捕捉異常是什麼意思?但除了例外情況外,還有其他更簡潔的方法嗎? – pencilCake 2010-02-26 09:44:27

+0

它爲我工作,但不知道有沒有其他方式來執行此操作...謝謝但Insted UnauthorizedAccessException異常我在我的代碼中使用IOException – 2010-02-26 10:05:27

+0

是的,與異常更好地檢查出哪一個扔在不同的場景。我只是讀了MSDN的描述,並拿起了一個看起來適合這個例子的。 – 2010-02-26 10:14:08

相關問題