如何释放filesystemwatcher锁定的文件

如何释放filesystemwatcher锁定的文件

本文介绍了如何释放filesystemwatcher锁定的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 FileSystemWatcher 在Paint上编辑图像文件时引发事件,并使用它更新预览图像控件。但是第二次将文件设置为源时,会抛出错误,因为该文件仍在被另一个进程使用。所以我发现这是因为 FileSystemWatcher



我尝试了什么:



I am using a FileSystemWatcher to raise the event when an image file is edited on Paint and update the preview image control using it. But setting the file as a source second time, it throws an error because the file is still in use by another process. So I discovered this is because of FileSystemWatcher.

What I have tried:

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

            ssreview.Source = bitmap;
        }





在这段代码中,我想在更新`Image`之前发布文件。我尝试过Dispose但它没有用。我怎么能这样做?



In this code I want to release the file before updating the `Image`. I tried Dispose but it was not worked. How can I do that?

推荐答案


这篇关于如何释放filesystemwatcher锁定的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:43