【发布时间】:2016-03-20 16:32:06
【问题描述】:
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);
【问题讨论】:
-
您可能喜欢阅读有关 MSDN: FileSystemWatcher 的内容,它会在目录或目录中的文件发生更改时侦听文件系统更改通知并引发事件。