【发布时间】:2023-11-19 06:49:01
【问题描述】:
你好我在网上搜索了这个异常, 我还没有找到解决方案,所以我决定问。 在控制台应用程序中,我需要在文件夹中搜索一定数量的 xml 文件。此类文件以 ANSI 编码。 应用程序所做的是获取文件并将其转换为 utf-8 编码。 但是随着循环的进行,会捕获此异常。 给定编码中的无效字符。第 1 行,位置 2757 我从第三个得到 xml 阿尔古纳的想法?非常感谢。 这是我的代码
我在 3 个 100 的 xmls 中得到了这个异常
int Count = 0;
string sNombre = "";
string targetPath = @"C:\SomePath\";
string logError = "log_xml_Error.log";
if (File.Exists(@"log_xml_Error.log"))
{
File.Delete(@"log_xml_Error.log");
}
Console.WriteLine("press enter");
Console.ReadLine();
string[] xmls = Directory.GetFiles(targetPath, "*.xml", SearchOption.AllDirectories);
foreach (var sFile in xmls)
{
try
{
Count++;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sFile);
byte[] sXmlByte = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);
sName = Path.GetFileName(sFile);
string sCompletePathXML = @"C:\SomePath\" + sName;
if (!File.Exists(sCompletePathXML))
{
File.WriteAllText(sCompletePathXML, System.Text.UTF8Encoding.UTF8.GetString(sXmlByte), System.Text.UTF8Encoding.UTF8);
}
Console.WriteLine(Count);
}
catch (Exception ex)
{
using (StreamWriter sw = File.AppendText(logError))
{
sw.WriteLine(" Error: " + ex.Message + "XML :" + sName);
}
}
}
Console.WriteLine("process complete");
Console.ReadLine();
【问题讨论】:
-
XML 文件是否包含指定编码的
<?xml ... ?>标记?