c# - 文件写入 3 次 C#

标签 c# utf-8

我有这段代码被重复了 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);
            }
        }
    }


  }  
 }

最佳答案

使用 FileSystemWatcher 的常见模式是在开始处理事件时将 EnableRaisingEvents 设置为 false:

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;
    }
}

关于c# - 文件写入 3 次 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14316308/

相关文章:

c# - 如何修复此 EventArgs c#

c# - 检索 MySQL 默认值

C# 与 C++ DLL 调用

codeigniter - 如何使用 CodeIgniter 将表情符号插入 MySQL

php - 如何在 PHP :json_encode 中使用 UTF-8

python - Pandas df.to_csv ("file.csv"encode ="utf-8")仍然为减号提供垃圾字符

c# - MONO 4.6.2 服务器 CPU 使用率高

c# - 在 C# 中使用 Prepare select 语句

ruby-on-rails - "\xFF"使用回形针从 ASCII-8BIT 到 UTF-8

eclipse - RCP 构建中的 UTF-8 字符