C#中String与byte[]的相互转换

  1. 从文件中读取字符串

    string filePath = @"C:Temp.xml";

    string xmlString= File.ReadAllText(filePath);

  2. 将字符串转为bytes

    byte[] buffer= System.Text.Encoding.UTF8.GetBytes(xmlString);

  3. bytes转为字符串

    string xmlString3 = System.Text.Encoding.UTF8.GetString(buffer);

这样做看似是没什么问题的,但是如果转换出的字符串要用于XmlDocument.LoadXml()时,就会出现以下错误:

System.Xml.XmlException:根级别上的数据无效。第一行,位置1

原因是大概是Utf8BOM的问题,在文件头出现了不可见字符,可通过如下方法解决:

var encoding = new UTF8Encoding(false, false);

string xmlString = encoding.GetString(buffer);

XmlDocument doc = new XmlDocument();

doc.LoadXml(xmlString);

参考:

  1. http://blog.csdn.net/freedom2028/article/details/8102455
原文地址:https://www.cnblogs.com/lightmao/p/6700317.html