0

I am using FileSystemWatcher to get the latest image from my Assets folder, i have a webcam to capture the image and save it in the Assets folder. After saving the image i get the latest image from FileSystemWatcher event. Here is my code :

 //FileWatcher
 private void FileWatcher()
    {
        path = @"..\..\Assets\WebCamImage\";
        System.IO.FileSystemWatcher watcher = new FileSystemWatcher(path);
        watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;

        watcher.Changed += watcher_Changed;
        watcher.EnableRaisingEvents = true;
    }


 //Event
 void watcher_Changed(object sender, FileSystemEventArgs e)
    {                 
      CustomerImage.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
    new Action(
        delegate()
        {                     
       CustomerImage.Source = (ImageSource)isc.ConvertFromString(e.FullPath);
        }
        ));
    }    

At page load event the source of CustomerImage control is set to a default picture which is nopictureavail.jpeg, when a changes made in that particular Directory the image should populate in CustomerImage, filewatcher event fires then the error throws at

CustomerImage.Source = (ImageSource)isc.ConvertFromString(e.FullPath);

NullReferenceException Occured in presentationCore.dll

Raj M
  • 1
  • 2

2 Answers2

0

Try to add this:

bitmap.CreateOption = BitmapCreateOptions.IgnoreImageCache

Here's some more

https://stackoverflow.com/a/1689808/2609288

Community
  • 1
  • 1
Galma88
  • 2,398
  • 6
  • 29
  • 50
  • i have changed my code, the previous was not working, kindly go through the edited one and gimme ur suggestions. – Raj M Mar 12 '15 at 16:53
0

You're getting this error because WPF holds on to the handle from its images. Try using this code instead:

BitmapImage image = new BitmapImage();
try
{
    using (FileStream stream = File.OpenRead(filePath))
    {
        image.BeginInit();
        image.StreamSource = stream;
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.EndInit();
    }
}
catch { return DependencyProperty.UnsetValue; }

I have this code in an IValueConverter to avoid a similar problem.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
  • You asked a question and I answered it. You're really not supposed to change your question to ask another question after it's been answered. If you have another question, then you should ask a new question and possibly provide a link to the original question if you want to provide some context. – Sheridan Mar 14 '15 at 12:49