2010-02-26 71 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

相关问题