1

私は3回繰り返されているこのコードを持っています:

private static void convert(object source, FileSystemEventArgs f)
{
    string FileName;
    FileName = f.FullPath;

    string destinationFile = @"Y:\test\test.xml";
              System.Threading.Thread.Sleep(2000);
   try
   {

        Encoding utf8 = new UTF8Encoding(false);
        Encoding ansi = Encoding.GetEncoding(1256);
        System.Threading.Thread.Sleep(2000);

        string xml = File.ReadAllText(FileName, ansi);
       XDocument xmlDoc = XDocument.Parse(xml);
            **Console.WriteLine("1st");**
            File.WriteAllText(
               destinationFile,
                @"<?xml version=""1.0"" encoding=""utf-8""?>" + xmlDoc.ToString(),
               utf8
            );
    }

上記を太字で確認してください。3回書きます。私はそれをテストするために置いたところです。しかし、なぜそれが3回書き出されるのでしょうか。つまり、書き込まれているファイルも3回書き込まれます。

filesystemwatcher関数からこの関数を呼び出して、フォルダーが変更されているかどうかを監視し、ファイルを取得してutf-8に変換し、宛先ファイルに配置します。

編集1:これが私のウォッチャーです。これで問題ないか確認してください。

private static void WatchFile()
    {
                watcher.Path = @"C:\project";

                   watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.xml";


        watcher.Changed += new FileSystemEventHandler(convert);
        watcher.Error += new ErrorEventHandler(WatcherError);
        Console.WriteLine("2nd");
        watcher.EnableRaisingEvents = true;


    }

それが3回繰り返される理由はまだわかりません。

編集2:

これが私の完全なコードです:

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;





class Test
{
 class Class1
{
    private static FileSystemWatcher watcher =
       new FileSystemWatcher();

    public static void Main()
    {
        WatchFile();
      Console.ReadLine();
     }

    private static void WatchFile()
    {
        watcher.Path = @"C:\project";

                    watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.xml";


        watcher.Changed += new FileSystemEventHandler(convert);
        watcher.Error += new ErrorEventHandler(WatcherError);
        Console.WriteLine("2nd");
        watcher.EnableRaisingEvents = true;

    }

    public static string CrL = "\r\n";

    private static void convert(object source, FileSystemEventArgs f)
    {
        string FileName;
        FileName = f.FullPath;

               string destinationFile = @"Y:\test\OnAirNow.xml";

                 System.Threading.Thread.Sleep(2000);
       try
       {

            Encoding utf8 = new UTF8Encoding(false);
            Encoding ansi = Encoding.GetEncoding(1256);
            System.Threading.Thread.Sleep(2000);

            string xml = File.ReadAllText(FileName, ansi);
           XDocument xmlDoc = XDocument.Parse(xml);
                Console.WriteLine("1st");
                File.WriteAllText(
                   destinationFile,
                    @"<?xml version=""1.0"" encoding=""utf-8""?>" + xmlDoc.ToString(),
                   utf8
                );



        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }


    }

    private static void WatcherError(object source, ErrorEventArgs e)
    {

        Exception watchException = e.GetException();
                   watcher = new FileSystemWatcher();
        while (!watcher.EnableRaisingEvents)
        {
            try
            {
                                   WatchFile();
                Console.WriteLine("I'm Back!!");
            }
            catch
            {
                                    System.Threading.Thread.Sleep(2000);
            }
        }
    }


  }  
 }
4

2 に答える 2

3

を使用する一般的なパターンは、イベントの処理を開始するときにFileSystemWatcherに設定することです。EnableRaisingEventsfalse

this.fileSystemWatcher = new FileSystemWatcher()
{
    Path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
    NotifyFilter = NotifyFilters.LastWrite,
    Filter = Path.GetFileName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
};

this.fileSystemWatcher.Changed += this.ConfigChanged;
this.fileSystemWatcher.EnableRaisingEvents = true;

public void ConfigChanged(object sender, FileSystemEventArgs e)
{
    try
    {
        this.fileSystemWatcher.EnableRaisingEvents = false;
        s_logger.Info("Configuration file changed.");
        // reload config here
        s_logger.Info("Configuration settings reloaded.");
    }
    catch (Exception exception)
    {
        s_logger.Error(exception.Message);
        s_logger.Error("Failed to reload configuration settings.");
    }
    finally
    {
        this.fileSystemWatcher.EnableRaisingEvents = true;
    }
}
于 2013-01-14T10:11:35.177 に答える
1

FileSystemWatcher は、1 つのファイル変更に対して複数のイベントを発生させる場合があります。確認してください。

一般的なファイル システム操作では、複数のイベントが発生する場合があります。たとえば、あるディレクトリから別のディレクトリにファイルを移動すると、いくつかの OnChanged イベント、いくつかの OnCreated イベント、および OnDeleted イベントが発生する可能性があります。ファイルの移動は、複数の単純な操作で構成される複雑な操作であるため、複数のイベントが発生します。同様に、一部のアプリケーション (ウイルス対策ソフトウェアなど) によって、FileSystemWatcher によって検出される追加のファイル システム イベントが発生する場合があります。

MSDN の FileSystemWatcher クラス

于 2013-01-14T10:25:15.313 に答える