调整csv阅读器以读取unicode字符

edi*_*ode 1 c# unicode

我有一个csv文件中的字符有问题,因为黑色钻石带有?在中间.

我已经编写了解析csv的代码,但我不明白为什么字符串没有正确读取unicode字符.这可能与我的实现有关:

StreamReader readFile = new StreamReader(path)

try {
  while ((line = readFile.ReadLine()) != null) {
    string[] row = { "", "", "" };
    int currentItem = 0;
    bool inQuotes = false;
    if (skippedFirst && currentItem != 3) {
      for (int i = 0; i < line.Length; i++) {
        if (!inQuotes) {
          if (line[i] == '\"')
            inQuotes = true;
          else {
            if (line[i] == ',')
              currentItem++;
            else
              row[currentItem] += line[i];
          }
        } else {
          if (line[i] == '\"')
            inQuotes = false;
          else
            row[currentItem] += line[i];
        }
      }
      parsedFile.Add(row);
    }
    skippedFirst = true;
  }
Run Code Online (Sandbox Code Playgroud)

mfu*_*ger 5

打开文件时指定编码.

using (var sr = new StreamReader(@"c:\Temp\csvfile.csv", Encoding.UTF8)) {
}
Run Code Online (Sandbox Code Playgroud)

您可能还想查看Filehelpers以进行CSV解析:

http://www.filehelpers.com/quick_start.html

  • 你确定 csv 是 utf8 编码的吗?也许这是不同的东西。Latin1 或类似的东西。编码的问题在于您*必须*知道它是什么,因为无法正确检测它。 (2认同)