Watch a Folder For Updates in WPF C#

In this example I am using a file system watcher to detect updates in a Windows folder. If a new file is added to the specified folder then it will provide notification of it in a listbox and open it. And when some changes are made to the file then notification of that is also done and the modified file will be copied to another folder.

If a rename of a file in the folder occurrs then notification also occurs in the listbox. Also if a file is deleted then notification of that also occurs. The file system watcher has options for all these purposes. The following example is mainly dealing with the images.

When an image is copy and pasted to a folder, it will get a statement in the listbox regarding that. The image will also be opened in Microsoft Paint

When some modification is made to this image and it is saved, the statement regarding that will be put in the listbox and the file will be copied to another folder.

Step 1: Create a WPF application

WPF.gif

Step 2: Add a list box, start button and clear button to the main grid

<
Window x:Class="FileWatcherProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="806">
    <Grid>
        <Button Name="btnSatrt" Width="100" Height="25" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,12,18,0" Content="Start" />
        <ListBox Height="225" HorizontalAlignment="Left" Margin="12,43,0,0" Name="listBox1" VerticalAlignment="Top" Width="491" />
        <Button Name="btnClear" Width="100" Height="25" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,274,18,0" Content="Clear" />
    </Grid>
</
Window>

Step 3: In the cs page, first declare the file system watcher, as in:

FileSystemWatcher fs; //comes under the namespace Using System.IO;

Also add some variables:

DateTime fsLastRaised;
FileSystemWatcher fs;
string watchingFolder;
bool paintopen;
bool wordopen;
bool excelopen;

Step 4: In the start button click event add this code:

private void btnSatrt_Click(object sender, RoutedEventArgs e)
{
   
//the folder to be watched
    watchingFolder = "D:\\WatchFolder";
   
//initialize the filesystem watcher
    fs = new FileSystemWatcher(watchingFolder, "*.*");

    fs.EnableRaisingEvents = true;
    fs.IncludeSubdirectories =
true;
   
//This event will check for  new files added to the watching folder
    fs.Created += new FileSystemEventHandler(newfile);
   
//This event will check for any changes in the existing files in the watching folder
    fs.Changed += new FileSystemEventHandler(fs_Changed);
   
//this event will check for any rename of file in the watching folder
    fs.Renamed+=new RenamedEventHandler(fs_Renamed);
   
//this event will check for any deletion of file in the watching folder
    fs.Deleted+=new FileSystemEventHandler(fs_Deleted);
}

Add all the following events.

Step 5:  Use the following for if a new file is added to the folder:

#region file Added to the folder
protected void newfile(object fscreated, FileSystemEventArgs Eventocc)
{
  
try
   {
     
//to avoid same process to be repeated ,if the time between two events is more   than 1000 milli seconds only the second process will be considered
      if (DateTime.Now.Subtract(fsLastRaised).TotalMilliseconds > 1000)
      {
         
//to get the newly created file name and extension and also the name of the event occured in the watching folder
          string CreatedFileName = Eventocc.Name;
          FileInfo createdFile =
new FileInfo(CreatedFileName);
         
string extension = createdFile.Extension;
         
string eventoccured = Eventocc.ChangeType.ToString();   
 
         
//to note the time of event occured
          fsLastRaised = DateTime.Now;
         
//Delay is given to the thread for avoiding same process to be repeated
          System.Threading.Thread.Sleep(100);                  
         
//dispatcher invoke
          this.Dispatcher.Invoke((Action)(() =>
          {
             
//give a notification in the application about the change in folder
              listBox1.Items.Add("Newly Created File Name :" + CreatedFileName + ";  Event Occured  :" + eventoccured + ";  Created Time  :" + DateTime.Now.ToShortTimeString());
                  
             
//if image file is created ,to open it in ms paint application
              if (extension == ".jpg" || extension == ".png")
              {
                   Process.Start(
"mspaint", watchingFolder + "\\" + CreatedFileName);
              }
             
//if video file is created ,to open it in windows mwdia player application
              else if (extension == ".wmv" || extension == ".mov" || extension == ".avi")
              {
                   Process.Start(
"wmplayer", watchingFolder + "\\" + CreatedFileName);
              }
             
//if ms word file is created ,to open it in ms word application
              else if (extension == ".docx")
              {
                   Process.Start(
"WINWORD.EXE", watchingFolder + "\\" + CreatedFileName);
              }
             
//if excel file is created ,to open it in excel application
              else if (extension == ".xlsx")
              {
                   Process.Start(
"excel.exe", watchingFolder + "\\" + CreatedFileName);
              }
             
//if pdf file is created ,to open it in PDF application
              else if (extension == ".pdf")
              {
                   Process.Start(
"AcroRd32.exe", watchingFolder + "\\" + CreatedFileName);
              }
             
//if Flash file is created ,to open it in web browser
              else if (extension == ".swf")
              {
                   Process.Start(
"iexplore.EXE", watchingFolder + "\\" + CreatedFileName);
              }
              }));
          }
     }
    
catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
     }
    
finally
     {
     }
}
#endregion

Step 6: Use the following for when there is a change in the existing files in the watched folder, to create the notification in the listbox and also copy the file to another folder:

#region file changed
protected void fs_Changed(object fschanged, FileSystemEventArgs changeEvent)
{
    
//to get the changed file name and extension and also the name of the event occured in the watching folder
     string CreatedFileName = changeEvent.Name;
     FileInfo createdFile =
new FileInfo(CreatedFileName);
    
string extension = createdFile.Extension;
    
string eventoccured = changeEvent.ChangeType.ToString();
        
    
if (DateTime.Now.Subtract(fsLastRaised).TotalMilliseconds > 1000)
     {
          fsLastRaised = DateTime.Now;
         
//Create a folder to copy the file when updated (for a folder in network just change serverlocation ="\\\\(ip address for eg:192.168.22.22)\\(sharing folder name)";
          string serverlocation = "D:\\ServerFolder";
         
try
          {
              System.Threading.Thread.Sleep(100);
             
this.Dispatcher.Invoke((Action)(() =>
              {
                  
//Changes occurs in image, word or excel file will copy that file to another location
                   if (extension == ".jpg" || extension == ".png")
                   {
                        
//to display notification about the change in the listbox
                        listBox1.Items.Add("Changed File Name :" + changeEvent.Name + "; Event Occured :" + changeEvent.ChangeType.ToString() + "; Time of Modification :" +
DateTime.Now.ToShortTimeString());
                                  
                       
//to copy the modified file to another location
                        File.Copy(watchingFolder + "\\" + changeEvent.Name, serverlocation + "\\" + changeEvent.Name, true);
                     }
                }));
             }
            
catch (Exception ex)
             {
             }
         }
    }
#endregion

Step 7: Use the following for when there is a rename of an existing file in the watched folder and create the notification in the listbox:

#region file renamed
protected void fs_Renamed(object fschanged, RenamedEventArgs changeEvent)
{
   
try
    {
       
if (DateTime.Now.Subtract(fsLastRaised).TotalMilliseconds > 1000)
        {
             fsLastRaised = DateTime.Now;
             
             System.Threading.Thread.Sleep(100);
                  
            
//to get the name of the file before rename
             string oldname = changeEvent.OldName;
                    
            
this.Dispatcher.Invoke((Action)(() =>
             {
                
//to display a notification about the rename in listbox
                 listBox1.Items.Add("Renamed Object New Name :" + changeEvent.Name + ";  oldname  :" + changeEvent.OldName + ";  Event Occured :" + changeEvent.ChangeType.ToString() + ";
Time of Rename  :"
+ DateTime.Now.ToShortTimeString());
             }));
        }
    }
   
catch (Exception ex)
    {
    }
}
#endregion

Step 8: If there is a deletion of a file in the watched folder then notification in the listbox is created by the following:

#region file Deleted
protected void fs_Deleted(object fschanged, FileSystemEventArgs changeEvent)
{
   
try
    {
       
if (DateTime.Now.Subtract(fsLastRaised).TotalMilliseconds > 1000)
        {
            fsLastRaised = DateTime.Now;
            System.Threading.Thread.Sleep(100);
         
           
this.Dispatcher.Invoke((Action)(() =>
            {
               
//to display a notification about the delete in listbox
                listBox1.Items.Add("Deleted Object Name :" + changeEvent.Name + "; : Event Occured :" + changeEvent.ChangeType.ToString() +";  Time of Rename  :" +
DateTime.Now.ToShortTimeString());
            }));
         }
     }
    
catch (Exception ex)
     {
     }
}
#endregion

Step 9: Now run the application and press the start button, then copy and paste an image into the watched folder.

You will see a notification in the listbox of the application, also the image is opened in Microsoft Paint. (If not then ensure that \Microsoft Paint exists in the system or increase the delay time in the code (
System.Threading.Thread.Sleep(500);)).

Step 10 : Make some changes in the Image opened in Microsoft Paint, then save it.

You will see notification in the listbox and the modified file will appear in the server location folder.

Step 11: Rename the file in watched folder, also delete it to receive both notifications in the listbox.