mpe*_*pen 17 c# events filesystemwatcher
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);
}
}
Run Code Online (Sandbox Code Playgroud)
应该是非常自我解释.我正在尝试创建一个文件监视器,以便我可以自动为我排序视频...如何让程序无法终止?
我想保持它基于控制台,所以我可以调试它,但最终我想删除控制台,只是让它在后台运行(我想作为一项服务).
M.B*_*ock 22
也许是这样的:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
更新
本着帮助其他可能寻找类似解决方案的人的精神,正如@Mark在评论中所说,还有一种方法可以使用类的WaitForChanged方法FileSystemWatcher来解决这个问题:
class Program
{
static void Main(string[] args)
{
var fw = new FileSystemWatcher(@".");
while (true)
{
Console.WriteLine("added file {0}",
fw.WaitForChanged(WatcherChangeTypes.All).Name);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样做允许应用程序无限期地等待(或者直到时间被破坏)才能更改文件.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
只是EnableRaisingEvents显然.
找到了另一个可能更好的解决方案:
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);
}
}
Run Code Online (Sandbox Code Playgroud)