テキストファイルが変更されたかどうかを確認するアプリを作成しようとしています。その場合は、Windows サービスを再起動します。
私は FileSystemWatcher を使用していますが、いくつかのイベントを生成しているようです。これが私のコードです:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.ServiceProcess;
using System.Threading;
namespace ConsoleApplication1
{
class FileMon
{
public static bool status;
public static void Run()
{
try
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"D:\test\";
watcher.Filter = "*.txt";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.EnableRaisingEvents = true;
Console.WriteLine(status);
while (Console.Read() != 'q') ;
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
static void watcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.ChangeType);
// status = true;
Console.WriteLine(status);
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
Console.WriteLine("before IF block status = {0} ", status);
if (status == false)
{
RestartService();
status = true;
Console.WriteLine("after IF block status = {0} ", status);
}
else
{
}
}
public static void RestartService()
{
ServiceController service = new ServiceController("6to4");
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(50);
Console.WriteLine("trying to stop");
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// Console.ReadKey();
Console.WriteLine("stoping.........");
// count the rest of the timeout
// int millisec2 = Environment.TickCount;
// timeout = TimeSpan.FromMilliseconds(50 - (millisec2 - millisec1));
Console.WriteLine("dd");
// Console.ReadKey();
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
}
}
それを実行し、テキスト エディターでテキスト ファイルを変更すると、次の出力が得られます。
False
Changed
False
File: D:\test\1.txt Changed
before IF block status = False
trying to stop
after IF block status = True
Changed
True
File: D:\test\1.txt Changed
before IF block status = True
Changed
True
File: D:\test\1.txt Changed
before IF block status = True
どこかにバグがあるように見えます。そのため、単一の変更後に出力のコピーが 1 つではなく 3 つ表示されます。そして、何が間違っていて、どこを間違えたのか理解できません....