[英]Filesystem watcher to pick and convert XML encoding
I'm using the filesystem watcher to pick and convert the encoding of a file, the file gets copied at the destination but without conversion. 我正在使用文件系统观察器来选择和转换文件的编码,该文件在目标位置被复制但没有转换。 I was using the below code earlier: 我之前使用的是以下代码:
string xml = File.ReadAllText(FileName,ansi);
XDocument xmlDoc = XDocument.Parse(xml);
Console.WriteLine("1st");
File.WriteAllText(
FileName,
@"<?xml version=""1.0"" encoding=""utf-8""?>" + xml.ToString(),
utf8
);
if (File.Exists(destinationFile))
File.Delete(destinationFile);
File.Copy(FileName, destinationFile,true);
Console.WriteLine("File Copied" + " " + DateTime.Now.ToString("HH:mm:ss tt")); // for troubleshoooting only
Console.WriteLine("Press \'q\' to quit.");
Console.Write(CrL);
But this is not working now , as the xml file I'm getting now contains the following header: 但这现在不起作用,因为我现在获取的xml文件包含以下标头:
<?xml version="1.0" encoding="WINDOWS-1256"?>
I was earlier suggested the below code: 之前曾向我建议以下代码:
var doc = new XmlDocument();
doc.Load(FileName);
XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent=true };
using (var fileStream = File.OpenWrite(destinationFile))
{
using (var writer = XmlWriter.Create(fileStream, settings))
{
doc.Save(writer);
}
}
But this is not doing the conversion at all. 但这根本不进行转换。 The dest. 目的。 file is still ansi. 文件仍然是ansi。 It's not doing the conversion to utf8. 它没有进行到utf8的转换。 Am I doing something wrong here 我在这里做错什么吗
You're rewriting the output file (the file written by XmlWriter
) with the original one by this code: 您将通过以下代码用原始文件重写输出文件( XmlWriter
编写的文件):
if (File.Exists(destinationFile))
File.Delete(destinationFile);
File.Copy(fileName, destinationFile, true);
Just remove these lines of code. 只需删除这些代码行。
Writing the XML-document using Windows-1256 encoding: 使用Windows-1256编码编写XML文档:
var settings = new XmlWriterSettings
{
Encoding = Encoding.GetEncoding("windows-1256"),
Indent = true
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.