Search code examples
c#.netfilesystemwatcher

How do you get the name of a new file created using FileSystemWatcher?


I'm monitoring a folder using FileSystemWatcher. If I download a file into there, how do I get the name of that downloaded file? For example, if I downloaded a file named TextFile.txt, how would I have it return that as a string? I am assuming this will work for all four triggers (changed, created, deleted, renamed)? I have IncludeSubdirectories set to true, so it should be able to do that.


Solution

  • On the OnCreated event, add this code:

    private void watcher_OnCreated(object source, FileSystemEventArgs e)
    {
        FileInfo file = new FileInfo(e.FullPath);
        Console.WriteLine(file.Name); // this is what you're looking for.
    }
    

    See FileInfo Class @ MSDN