如何在目录中搜索名称未知的文件类型

时间:2019-05-15 16:25:10

标签: c# search directory

我正在运行一个使用switch大小写来完成一系列命令的例程。第一步是等待一个名称未知的.csv文本文件,由另一个程序生成该文件并执行一些分析。

我已经看到了使用FileSystemWatcher的建议,但这依赖于我已经在例程中间的句柄。

Switch (command)
{
  case "WAIT":
   {
     while(bool found = false)
     {
       if(//NEW .csv file in a known directory exists)
          {
            found = true;
          }
       Thread.Sleep(100);
     }
     //do some stuff with the .csv file.
     break;
   }

}

简单地说,当在目录中找到新的.csv文件时,将对其进行检查并移至例程的下一步。

2 个答案:

答案 0 :(得分:1)

您可以使用csv在目录中搜索任何已创建的FileSystemWatcher文件。代替您的while循环,请使用:

using (var watcher = new FileSystemWatcher(directoryPath, "*.csv"))
{
     watcher.EnableRaisingEvents = true;
     var watcherCreatedFile = watcher.WaitForChanged(WatcherChangeTypes.Created); 
    //this will wait for a file to be created

    if (watcherCreatedFile.ChangeType == WatcherChangeTypes.Created)
    {
        //will trigger when a file is created
        string fileNameCreated = watcherCreatedFile.Name;
    }
}

答案 1 :(得分:1)

我不知道您到底要什么。但是也许这样的方法应该可以:

public void ProcessCsvFile(){
    using (FileSystemWatcher watcher = new FileSystemWatcher())
    {
        watcher.Path = args[1];         

        // Only watch text files.
        watcher.Filter = "*.txt";

        // Add event handlers.     
        watcher.Created += (source,e)=>ProcessImportFile(e.FullPath);

        // Begin watching.
        watcher.EnableRaisingEvents = true;

        Console.WriteLine("Waiting for the file");
        Console.Read();
    }    
}

您必须创建filesystemwatcher和一个处理程序来管理所创建的事件,该事件将在有人将文件放入该文件夹时引发。