【发布时间】:2014-07-23 21:52:57
【问题描述】:
最近我偶然发现了一个关于 UTF8 的问题。我被要求以 UTF8 编码写入和读取文件。乍一看,我认为这很容易,但事实并非如此。 我的问题是我必须编写一个包含字符串和整数或短整数的二进制文件。 为此,我写了
byte[] BOM = new byte[] {0xEF, 0xBB, 0xBF};
byte[] Head;
byte head4[] = new byte[4];
UTF8Encoding utf8 = new UTF8Encoding(false);
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
stream.Write( BOM,0, BOM.Length);
Byte[] title = utf8.GetBytes("Hello_Abra");
stream.Write(title, 0, title.Length);
string HeadString = new string('\0', INDEXLength);
Head = utf8.GetBytes(HeadString);
stream.Write( Head, 0, Head.Length);
WriteInt(1258, head4, 0 );
stream.Write( head4, 0, head4.Length);
}
public static void WriteInt(int TheInt, byte[] ToArray, int atIndex)
{
for (int i=0; i<limit; i++)
{
byte thebyte = (byte) (TheInt & 0xff);
ToArray[atIndex+i] = thebyte;
TheInt = TheInt>>8;
}
}
当我调用 WriteInt 函数获取整数值并尝试将其写入文件时,结果文件的内容始终为 ANSI,所有字符均以 ANSI 格式写入。 另一方面,如果我只写字符串,则文件内容为 UTF8,字符串以 2 字节 UFT8 格式写入。
怎么了。这是实现目标的正确方法。 任何帮助表示感谢。
乔斯
【问题讨论】:
标签: utf-8