Faraday
Faraday

Reputation: 1

Folder monitoring - Deleting files after process has completed

I am running a FileWatcher in a folder that is looking for a files with extension .stl and .txt

watcher.Filter = "*.stl"; 

watcher.Filter = "*.txt";

These files are added to the FileWatcher folder at the same time, and once they are added, I have a process set to run.

Once this process exits, I need to have both files (.stl and .txt) deleted from the folder they were added to.

How can I go about doing this?

I can get the path of the added files through fullPath = e.FullPath;

Once my process completes and exits I have it check if the File extension exists, and if so, deletes it.

process.Exited += new EventHandler(myProcess_Exited);

process.WaitForExit();



 private static void myProcess_Exited(object sender, System.EventArgs e)
        {
            if (File.Exists(@fullPath))
            {
                File.Delete(@fullPath);
            }
        }

My code is able to successfully complete, but it is only deleting the .txt file, and I need it to delete the .stl as well.

Upvotes: -1

Views: 127

Answers (1)

user16612111
user16612111

Reputation:

All you need to do is use a list to hold the full paths of the two files, add the paths of the files to the list when a new file is added to the folder using the File Created event like in the code below

//list to hold the full paths of the two files, declare this in your class
var list = new List<string>();
//create a new File System Watcher object
var systemWatcher = new FileSystemWatcher();
//set the path who listen for file events
systemWatcher.Path = "myfolder";
//enable raising of events
systemWatcher.EnableRaisingEvents = true;
//subscribe to file created events 
systemWatcher.Created += SystemWatcher_Created;

//thuis method is fired when new files are added to the path 
private void SystemWatcher_Created(object sender, FileSystemEventArgs e){
 //add the full path of the files added to the list
 list.Add(e.FullPath);
}

Then on your method which listens if the process has exited, iterate through the list and delete both files from the directory.

private static void myProcess_Exited(object sender, System.EventArgs e)
        {
          foreach(var filePath in list)
          {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
          }
        }

Upvotes: 0

Related Questions