2012-02-14 65 views
3

可能重复:
Is there a way to check if a file is in use?
Check if a file is open我怎么知道文件已经打开或正在使用?

我怎么能知道文件已打开或使用。

public bool FileIsLocked(string strFullFileName) 
     { 
      bool blnReturn = false; 
      System.IO.FileStream fs; 
      try 
      { 
       fs = System.IO.File.Open(strFullFileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None); 
       fs.Close(); 
      } 
      catch (System.IO.IOException ex) 
      { 
       blnReturn = true; 
      } 
      return blnReturn; 
     } 

我觉得上面的代码不能正常工作

+0

http://stackoverflow.com/questions/1304/how-继承to-check-for-file-lock-in-c – vulkanino 2012-02-14 13:14:55

+1

请注意,您使用的功能如th在使用它时,可能会过时。文件可以被锁定,您检查的文件不是,反之亦然。通常最好尝试用你需要的任何文件处理,并在出现错误时作出反应。 – 2012-02-14 13:18:03

+0

我得到这个代码,但它不能正常工作 – bkac 2012-02-14 13:21:07

回答

0

由于从这里取:Is there a way to check if a file is in use?

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

     try 
     { 
      stream = file.Open(FileMode.Open, FileAccess.ReadWrite, 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

我已经回答了之前在这里:Check if a file is open

编辑

FileInfo file = new FileInfo(path); 

功能

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

    try 
    { 
     stream = file.Open(FileMode.Open, FileAccess.ReadWrite, 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(); 
    } 
    return false; 
} 
+0

但什么是FileInfo ??? – bkac 2012-02-14 13:18:16

+0

@bkac - 检查更新的答案................. – 2012-02-14 13:23:40

+0

以及它仍然无法正常工作 – bkac 2012-02-14 13:28:26

相关问题