C#写入文件>>第一字节顺序问题 [英] C# write to file >> first byte-order problem

查看:85
本文介绍了C#写入文件>>第一字节顺序问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道您是否可以在以下方面提供帮助:

I was wondering if you could help with the below:

我有一个名为test.xml的XML文件,我需要进行一些修改,该XML文件的外观类似于下面的

I have an XML file called test.xml that I need to do some modify, XML file looks similar to the below

<?xml version="1.0" encoding="utf-8"?>
  <someNode>
     <someOtherNode>blah blah<someOtherNode>
  </someNode>

=======================

=========================

private string Beautify_XML(XmlDocument doc)
{
 //StringBuilder sb = new StringBuilder();
 MemoryStream stream = new MemoryStream(); 
 XmlWriterSettings settings = new XmlWriterSettings();
 settings.Indent = true;
 settings.IndentChars = " ";
 settings.NewLineChars = "\r\n";
 settings.NewLineHandling = NewLineHandling.Replace;
 settings.Encoding = Encoding.UTF8;
 using (XmlWriter writer = XmlWriter.Create(stream,  settings)) {doc.Save(writer); }
 return UTF8Encoding.UTF8.GetString(stream.ToArray());
} //end Beautify(XmlDocument doc)



==========================

===========================

修改后,我需要将其写回到test.xml

After the modification I need to write it back to the test.xml

我得到了一个如下函数,用于格式化返回字符串,然后再将其写回XML文件(覆盖)

I got a function as below just to format the return string before I write it back to the XML file (overwrite)

然后将其称为

string myBeautiful_XML_string = Beautify_XML(myXmlDocument);
//Now write it back to the XML 
System.IO.File.WriteAllText(my_xml_path, myBeautiful_XML_string);

问题是在写入XML文件后,文件开始处有一些奇怪的字符(树干),我用谷歌搜索,有人称它为第一字节顺序".

The problem is after the XML file is written, there is some weird character (trunk) at start of file, which I googled and someone call it "first byte-order".

我做错了什么?以及如何解决?预先谢谢你.

What have I done wrong? and how to fix it? Thanks you in advance.

推荐答案

我认为您不必为此担心.由于您提供了"encoding =" utf-8",因此,文件中的前3个字节为 UTF-8标识符(0xEF 0xBB 0xBF).通过这些字节 系统(和某些应用)识别要以UTF-8编码的内容.

I don't think you need to worry about it. Since you provided 'encoding="utf-8" the first 3 bytes in the file will be UTF-8 identifier (0xEF 0xBB 0xBF). By these bytes the system (and some apps) identify the contents to be encoded in UTF-8.

http://en.wikipedia.org/wiki/Byte_order_mark

这篇关于C#写入文件&gt;&gt;第一字节顺序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆