文件夹监控 - 进程完成后删除文件

问题描述 投票:0回答:1

我正在一个文件夹中运行 FileWatcher,该文件夹正在查找扩展名为 .stl 和 .txt 的文件

watcher.Filter = "*.stl"; 

watcher.Filter = "*.txt";

这些文件同时添加到 FileWatcher 文件夹中,添加后,我就设置了一个要运行的进程。

此进程退出后,我需要将这两个文件(.stl 和 .txt)从它们添加到的文件夹中删除。

我怎样才能做到这一点?

我可以通过

fullPath = e.FullPath; 

获取添加的文件的路径

一旦我的进程完成并退出,我就会检查文件扩展名是否存在,如果存在,则将其删除。

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

我的代码能够成功完成,但它只是删除.txt文件,我还需要它来删除.stl。

c# events process filesystemwatcher file-watcher
1个回答
0
投票

您需要做的就是使用一个列表来保存两个文件的完整路径,当使用“文件创建”事件将新文件添加到文件夹时,将文件的路径添加到列表中,如下面的代码所示

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

然后在侦听进程是否退出的方法上,迭代列表并从目录中删除这两个文件。

private static void myProcess_Exited(object sender, System.EventArgs e)
        {
          foreach(var filePath in list)
          {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
          }
        }
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.