C# XmlDocument未读取文件

C# XmlDocument未读取文件,c#,xml,openfiledialog,C#,Xml,Openfiledialog,我尝试读取xml文件并使用xml做一些事情。但是我在将文件加载到XmlDocument时遇到了一个问题。这里没有错误。但当加载时,程序崩溃,编译器说: 没有Unicode字节顺序标记。无法切换到Unicode 这是我的密码: Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.Filter = "xml (*.xml)|*.xml"; if (dlg.ShowDialog() == true

我尝试读取xml文件并使用xml做一些事情。但是我在将文件加载到XmlDocument时遇到了一个问题。这里没有错误。但当加载时,程序崩溃,编译器说:

没有Unicode字节顺序标记。无法切换到Unicode

这是我的密码:

Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "xml (*.xml)|*.xml";
if (dlg.ShowDialog() == true){
XmlDocument doc = new XmlDocument();
doc.Load(dlg.FileName);

文件不是unicode如果您不确定编码形式,可以执行以下操作:

//  path + filename !!
using (StreamReader streamReader = new StreamReader(dlg.FileName, true))
{
    XDocument xdoc = XDocument.Load(streamReader);
}
或者这样做:

XDocument xdoc = XDocument.Parse(System.IO.File.ReadAllLines(dlg.FileName));

仔细阅读链接,了解问题所在。 @ZachBurlingame溶液;你必须这样做:


它一定有用

XmlDoc应该能够在没有BOM的情况下读取ASCII和Unicode。但是这可能是有教育意义的,user3058140应该在调试器中运行它。检查XML标题。您是否看到类似的内容:@HenkHolterman it same类似于此问题:用户可以从XML中删除编码this encoding=“utf-16那么您不必做任何事情!或者您需要它?
// Encode the XML string in a UTF-8 byte array
byte[] encodedString = Encoding.UTF8.GetBytes(xml);

// Put the byte array into a stream and rewind it to the beginning
MemoryStream ms = new MemoryStream(encodedString);
ms.Flush();
ms.Position = 0;

// Build the XmlDocument from the MemorySteam of UTF-8 encoded bytes
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(ms);