gpt4 book ai didi

c# - 创建 UTF8 文本文件而不是 ANSI

转载 作者:行者123 更新时间:2023-11-30 14:34:57 24 4
gpt4 key购买 nike

我有这段代码可以异步写入文件:

    private static async Task WriteTextAsync(string filePath, string text)
{ //Writes to our output files
byte[] encodedText = Encoding.UTF8.GetBytes(text);
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Create, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};
}

尽管设置了 Encoding.UTF8,创建的文本文件仍然是 ANSI 格式。 FileStream 类有 15 个重载构造函数,如果不是在编码文本上,我根本不知道应该在哪里设置它。

我可以看出该文件是 ANSI,因为当我在 TextPad 中打开它并查看文件统计信息时,它会将 ANSI 列为代码集:

enter image description here

有问题,因为MySQL LOAD INFILE 没有正确读取文件,看了答案后我认为它与BOM有关,但不确定。

我试过这个(对于 BOM):

        byte[] encodedText = new byte[] { 0xEF, 0xBB, 0xBF }.Concat(Encoding.UTF8.GetBytes(text)).ToArray();
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Create, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};

Textpad 然后将其视为 UTF8,MySQL LOAD INFILE 仍然失败。重新保存在 Textpad 中,MySQL 正确地看到了它。

将代码更改为:

        using (TextWriter writer = File.CreateText(filePath))
{
await writer.WriteAsync(text);
}

这似乎对两者都有效。我不确定 MySQL LOAD INFILE 与此有关的问题是什么。

最佳答案

不对,肯定是UTF-8:

byte[] encodedText = Encoding.UTF8.GetBytes(text);

只能给你UTF-8;然后将 encodedText 写入流。

但是!对于 0-127 范围内的任何字符,UTF-8 看起来与 ASCII/ANSI 相同。它只是在上面看起来不同。误报?

关于c# - 创建 UTF8 文本文件而不是 ANSI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13032988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com