简体   繁体   English

XmlException给定编码中的无效字符

[英]XmlException Invalid character in the given encoding

Hello I searched the internet this exception, I have not found solution so I decided to ask. 您好,我在互联网上搜索了此例外情况,但尚未找到解决方案,因此我决定询问。 in a console application I need to search a folder a certain number of xml files. 在控制台应用程序中,我需要在文件夹中搜索一定数量的xml文件。 such file is encoded in ANSI. 此类文件以ANSI编码。 what the application does is to take the file and convert it to utf-8 encoding. 应用程序要做的是获取文件并将其转换为utf-8编码。 but as the cycle goes catch this exception. 但是随着周期的过去,会捕获到此异常。 Invalid character in the given encoding. 给定编码中的无效字符。 Line 1, position 2757 I get the xml from a third alguna Idea? 第1行,位置2757我从第三个alguna Idea获得了xml? muchas gracias. 更多。 this is my code 这是我的代码

i get this exception in 3 xmls of 100 我在100的3个xml中得到此异常

        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();

what the application does is to take the file and convert it to utf-8 encoding 应用程序要做的是获取文件并将其转换为utf-8编码

I would simle do 我会很高兴

var xdoc = XDocument.Parse(File.ReadAllText(filename,Encoding.ASCII));
File.WriteAllText(filename, xdoc.ToString(), Encoding.UTF8);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM