我正在使用FileSystemWatcher在Paint上编辑图像文件时引发事件,并使用它更新预览图像控件。但是第二次将文件设置为源时,会抛出错误,因为该文件仍在被另一个进程使用。所以我发现这是因为FileSystemWatcher。
我有这段代码:
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
if (!File.Exists(lastImage)) return;
FileSystemWatcher izleyici = new FileSystemWatcher(System.IO.Path.GetDirectoryName( lastImage),
System.IO.Path.GetFileName(lastImage));
izleyici.Changed += izleyici_Changed;
izleyici.NotifyFilter = NotifyFilters.LastWrite;
izleyici.EnableRaisingEvents = true;
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = lastImage;
info.Verb = "edit";
Process.Start(info);
}
void izleyici_Changed(object sender, FileSystemEventArgs e)
{
//I want to add code here to release the file. Dispose() not worked for me
setImageSource(lastImage);
}
void setImageSource(string file)
{
var bitmap = new BitmapImage();
using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
}
ssPreview.Source = bitmap;
}
在此代码中,我想在更新Image
控件之前释放该文件。我试过Dispose
但是没有用。我怎么能这样做?
答案 0 :(得分:2)
该文件既未被FileSystemWatcher锁定,也未被MS Paint锁定。实际发生的是你得到InvalidOperationException
,因为在UI线程中没有触发FileSystemWatcher的Changed
事件,因此处理程序方法无法设置Image控件的Source
属性。
在Dispatcher操作中调用图像加载代码可以解决问题:
void setImageSource(string file)
{
Dispatcher.Invoke(new Action(() =>
{
using (var stream = new FileStream(
file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
ssPreview.Source = BitmapFrame.Create(
stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
}));
}