我有这个重复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);
}
}
}
}
}