简体   繁体   English

FileSystemWatcher OnCreated返回的字符串?

[英]FileSystemWatcher OnCreated returning string?

I would like to make the FileSystemWatcher monitor a folder and once there is a file created inside to get the filename so after that file could be read by File.OpenRead() and a StreamReader 我想让FileSystemWatcher监视一个文件夹,并且一旦在内部创建了一个文件来获取文件名,因此在该文件之后可以被File.OpenRead()和StreamReader读取。

I have seen a lot of examples but not my case exactly: 我已经看到了很多例子,但我的情况并非如此:

        public static void FileWatcher()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"C:\Users\";
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.txt";
        watcher.Created += new FileSystemEventHandler(OnCreated);
        watcher.EnableRaisingEvents = true;
    }

    public static void OnCreated(object source, FileSystemEventArgs e)
    {
        string filename = Path.GetFileName(e.FullPath);
    }

My question is how to get the filename that is going to be created in that folder and pass its path and file to since the event method is a void: 我的问题是如何获取将在该文件夹中创建的文件名,并将其路径和文件传递到该文件,因为事件方法是无效的:

const string fileName = @"C:\Users\.txt";
        using (var stream = File.OpenRead(fileName))
        using (var reader = new StreamReader(stream))

Any help appreciated! 任何帮助表示赞赏!

I'd recommend encapsulating your file processing in a separate class. 我建议将文件处理封装在单独的类中。

public class FileProcessor
{
      public void ProcessFile(string filePath)
       {
           using (var stream = File.OpenRead(filePath))
           //etc...

       }
}

Then instance it and call it. 然后实例化它并调用它。

 public static void OnCreated(object source, FileSystemEventArgs e)
    {
       var processor = new FileProcessor();
       processor.ProcessFile(e.FullPath);
    }

Or if your method is in the same class as the Created event 或者,如果您的方法与Created事件在同一类中

YourMethodName(e.FullPath);

And your method should have a signature like this 而且你的方法应该有这样的签名

void YourMethodName (string filePath)
{
  //Process file
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM