2015-12-15 20 views
0
private void DisplayLastTakenPhoto() 
{ 
    string mypath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),"RemotePhoto"); 
    var directory = new DirectoryInfo(mypath); 
    var myFile = directory.EnumerateFiles() 
     .Where(f => f.Extension.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || f.Extension.Equals("raw", StringComparison.CurrentCultureIgnoreCase)) 
     .OrderByDescending(f => f.LastWriteTime) 
     .First(); 

    LiveViewPicBox.Load(myFile.FullName); 
} 

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; 
} 

的問題是與線:如何等待文件可用?

LiveViewPicBox.Load(myFile.FullName); 

有時它的正常工作,有時我得到這條線上例外說該文件是由另一個進程使用。

所以我想使用IsFileLocked方法或其他一些方法來檢查,直到文件沒有被鎖定。 但是,如果我將調用此方法前行

LiveViewPicBox.Load(myFile.FullName); 

它會檢查文件鎖定只有一次。我需要以某種方式使用while或者其他方式來檢查文件是否被反覆鎖定,直到它被解鎖。 並且只有當它被解鎖才能使行LiveViewPicBox.Load(myFile.FullName);

+0

您可能會喜歡閱讀[MSDN:FileSystemWatcher](https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v = vs.110).aspx)它會監聽文件系統更改通知並在目錄或目錄中的文件發生更改時引發事件。 –

回答

-2
public static bool IsFileReady(String sFilename) 
{ 
    // If the file can be opened for exclusive access it means that the file 
    // is no longer locked by another process. 
    try 
    { 
     using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None)) 
     { 
      if (inputStream.Length > 0) 
      { 
       return true; 
      } 
      else 
      { 
       return false; 
      } 

     } 
    } 
    catch (Exception) 
    { 
     return false; 
    } 
} 

將其置於循環中並等待它返回true。

+0

這不是一個真正的答案。它可以返回true,並在一毫秒後再次被鎖定。 –

+0

@cFrozenDeath他特別要求一種方法來檢查文件被一直解鎖,他沒有要求一種方法來鎖定文件。 – user1598725

+0

這不是專業的,很好的複製粘貼答案,無需添加任何東西。顯然應該被標記爲重複爲我評論或從您採取的答案的地方:http://stackoverflow.com/questions/50744/wait-until-file-is-unlocked-in-net –