UTF8 字符写入文件时丢失
UTF8 Character lost when written to file
我正在创建一个应用程序来扫描和合并 CSV 文件。将数据写入新文件时遇到问题。其中一个字段具有 ö 字符,该字符会一直保留到我将其写入新文件为止。然后它变成 "actual" 值:ö 而不是 "expected" 值:ö
我怀疑 UTF8 编码不是最好用的,但还没有找到更好的工作方法。如有任何帮助,我们将不胜感激!
</p>
<pre><code>byte[] nl = new UTF8Encoding(true).GetBytes("\n");
using (FileStream file = File.Create(filepath))
{
string text;
byte[] info;
for (int r = 0; r < data.Count; r++)
{
int c = 0;
for (; c < data[r].Count - 1; c++)
{
text = data[r][c] + @",";
text = text.Replace("\n", @"");
text = text.Replace(@"☼", @"""");
info = new UTF8Encoding(true).GetBytes(text);
file.Write(info, 0, text.Length);
}
text = data[r][c];
info = new UTF8Encoding(true).GetBytes(text);
file.Write(info, 0, text.Length);
file.Write(nl, 0, nl.Length);
}
}
我可能弄错了,这可能应该放在评论中,但我还不能评论。文本编辑器会将二进制数据解码成某种编码。您可以在十六进制编辑器中检查实际的二进制数据。您可以验证写入文件的二进制数据。 Notepad++ 有一个十六进制编辑器插件,你可以使用。
BinaryWriter 在将字节写入文件时更容易使用。您还可以设置 BinaryWriter 的编码。您需要将其设置为 UTF-8。
编辑
忘记说了。当您写出字节时,您也将希望以字节的形式读入。使用 BinaryReader 并将编码设置为 UTF-8。
读取正在使用的字节后Encoding.UTF8.GetString()将字节转换为字符串。
您可能会截断输出,因为 UTF-8 是多字节的。
不要这样做:
info = new UTF8Encoding(true).GetBytes(text);
file.Write(info, 0, text.Length);
改为使用info.Length
。
info = new UTF8Encoding(true).GetBytes(text);
file.Write(info, 0, info.Length); // change this line
我正在创建一个应用程序来扫描和合并 CSV 文件。将数据写入新文件时遇到问题。其中一个字段具有 ö 字符,该字符会一直保留到我将其写入新文件为止。然后它变成 "actual" 值:ö 而不是 "expected" 值:ö
我怀疑 UTF8 编码不是最好用的,但还没有找到更好的工作方法。如有任何帮助,我们将不胜感激!
</p>
<pre><code>byte[] nl = new UTF8Encoding(true).GetBytes("\n");
using (FileStream file = File.Create(filepath))
{
string text;
byte[] info;
for (int r = 0; r < data.Count; r++)
{
int c = 0;
for (; c < data[r].Count - 1; c++)
{
text = data[r][c] + @",";
text = text.Replace("\n", @"");
text = text.Replace(@"☼", @"""");
info = new UTF8Encoding(true).GetBytes(text);
file.Write(info, 0, text.Length);
}
text = data[r][c];
info = new UTF8Encoding(true).GetBytes(text);
file.Write(info, 0, text.Length);
file.Write(nl, 0, nl.Length);
}
}
我可能弄错了,这可能应该放在评论中,但我还不能评论。文本编辑器会将二进制数据解码成某种编码。您可以在十六进制编辑器中检查实际的二进制数据。您可以验证写入文件的二进制数据。 Notepad++ 有一个十六进制编辑器插件,你可以使用。
BinaryWriter 在将字节写入文件时更容易使用。您还可以设置 BinaryWriter 的编码。您需要将其设置为 UTF-8。
编辑
忘记说了。当您写出字节时,您也将希望以字节的形式读入。使用 BinaryReader 并将编码设置为 UTF-8。
读取正在使用的字节后Encoding.UTF8.GetString()将字节转换为字符串。
您可能会截断输出,因为 UTF-8 是多字节的。
不要这样做:
info = new UTF8Encoding(true).GetBytes(text);
file.Write(info, 0, text.Length);
改为使用info.Length
。
info = new UTF8Encoding(true).GetBytes(text);
file.Write(info, 0, info.Length); // change this line