How do I get this event-based console app to not terminate immediately?

mpen picture mpen · Dec 30, 2011 · Viewed 10.5k times · Source

Source

class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
        fw.Created+= fw_Created;
    }

    static void fw_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("added file {0}", e.Name);
    }
}

Question

Should be pretty self explanatory. I'm trying to create a file watcher so I can sort my videos for me automatically...how do I get the program to not terminate, ever?

I want to keep it console-based for now so I can debug it, but eventually I want to remove the console and just have it run in the background (I guess as a service).

Answer

M.Babcock picture M.Babcock · Dec 30, 2011

Perhaps something like this:

class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
        fw.Changed += fw_Changed;
        fw.EnableRaisingEvents = true;

        new System.Threading.AutoResetEvent(false).WaitOne();
    }

    static void fw_Changed(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("added file {0}", e.Name);
    }
}

Update

In the spirit of helping anyone else that may be looking for a similar solution, as @Mark stated in the comments, there is also a way to use the WaitForChanged method of the FileSystemWatcher class to solve this question:

class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@".");
        while (true)
        {
            Console.WriteLine("added file {0}",
                fw.WaitForChanged(WatcherChangeTypes.All).Name);
        }
    }
}

Doing so allows the application to wait indefinitely (or until the while is broken) for a file to be changed.