字节[]中字符串数据的编码检测成功,之后所有字符串比较都失败

本文关键字:字符串 之后 成功 比较 失败 检测 数据 编码 字节 | 更新日期: 2023-09-27 17:50:05

如何设置:

  • 我收到一个包含CSV数据的byte[]
  • 我不知道编码(应该是unicode/utf8)
  • 我需要检测编码或退回到默认值(文本可能包含变音符,所以编码很重要)
  • 我需要读取标题行并将其与定义的字符串进行比较

经过简短的搜索,我如何从byte[]中获得字符串,我发现如何将字节[]转换为字符串?它说要使用像

这样的东西
string result = System.Text.Encoding.UTF8.GetString(byteArray);

我(知道)使用这个助手来检测编码,然后Encoding.GetString方法读取字符串,如下所示:

string csvFile = TextFileEncodingDetector.DetectTextByteArrayEncoding(data).GetString(data);

但是,当我现在尝试比较值从这个result字符串与静态字符串在我的代码所有比较失败!

// header is the first line from the string that I receive from EncodingHelper.ReadData(data)
for (int i = 0; i < headers.Count; i++) {
    switch (headers[i].Trim().ToLower()) {
        case "number":
            // do
            break;
        default:
            throw new Exception();
    }
}
// where (headers[i].Trim().ToLower()) => "number"

虽然这似乎是两个字符串的编码问题,我的问题是:

我如何从byte[]检测string的编码并将其转换为默认编码,以便我能够使用该字符串数据?


编辑

只要字符串数据来自这样保存的文件,上面提供的代码就可以工作:

string tempFile = Path.GetTempFileName();
StreamReader reader = new StreamReader(inputStream);
string line = null;
TextWriter tw = new StreamWriter(tempFile);
fileCount++;
while ((line = reader.ReadLine()) != null)
{
    if (line.Length > 1)
    {
        tw.WriteLine(line);
    }
}
tw.Close();

,然后用

读出
File.ReadAllText()

。强制文件为unicode (ANSI格式杀死所有的小写字母)

B。要求写入文件可访问

现在我只得到了inputStream并尝试了我上面发布的内容。正如我之前提到的,这是可行的,弦看起来是一样的。但事实并非如此。

注意:如果我使用ANSI编码文件,它使用Encoding.Default都可以正常工作。


编辑2

当ANSI编码数据工作时,UTF8编码(notepadd++只显示UTF-8而不是w/o BOM)以char [0]: 65279开头

所以哪里是我的错误,因为我猜System.Text.Encoding.UTF8.GetString(byteArray)是正确的工作方式。

字节[]中字符串数据的编码检测成功,之后所有字符串比较都失败

是的,Encoding.GetString不会剥离BOM(参见https://stackoverflow.com/a/11701560/613130)。你可以:

string result;
using (var memoryStream = new MemoryStream(byteArray))
{
    result = new StreamReader(memoryStream).ReadToEnd();
}

StreamReader将自动检测编码(您的编码检测器是StreamReader.DetectEncoding()的副本)