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);
}
}
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).
Because it's finished. When console applications have completed executing and return from their main method, the associated console window automatically closes.
You can off course put #if DEBUG and #endif around the Console calls, but if you really want to prevent the window from closing only on your dev machine under Visual Studio or if VS isn't running only if you explicitly configure it, and you don't want the annoying 'Press any key to exit...' when running from the ...
Keep Console Open With the Ctrl + F5 Shortcut in C# The best approach for keeping our console window open after the execution of code is to run it with the Ctrl + F5 shortcut of the Microsoft Visual Studio IDE.
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.
class Program
{
static void Main(string[] args)
{
var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
fw.EnableRaisingEvents = true;
fw.Created += fw_Created;
Console.ReadLine();
}
static void fw_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("added file {0}", e.Name);
}
}
Just had to EnableRaisingEvents
apparently.
Found another solution that is perhaps even nicer:
class Program
{
static void Main(string[] args)
{
var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
fw.Created += fw_Created;
while(true) fw.WaitForChanged(WatcherChangeTypes.All);
}
static void fw_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("added file {0}", e.Name);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With