【发布时间】:2016-08-28 13:11:24
【问题描述】:
当在 Paint 上编辑图像文件并使用它更新预览图像控件时,我正在使用 FileSystemWatcher 引发事件。但是第二次将文件设置为源,它会引发错误,因为该文件仍在被另一个进程使用。所以我发现这是因为 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,但没有成功。我该怎么做?
【问题讨论】:
标签: wpf filesystemwatcher