如何在c#.net中检索csv文件的编码?

时间:2011-06-07 13:36:49

标签: c# encoding csv format

我需要获取csv文件的编码类型,如何在c#.net中执行此操作。

我在UTF8编码期间避免添加字节顺序映射(BMO)的代码如下:

     public static void SaveAsUTF8WithoutByteOrderMark(string fileName, Encoding encoding)
     {
        if (fileName == null)
             throw new ArgumentNullException("fileName");

    if (encoding == null)
    {
        encoding = Encoding.Default;
    }

    File.WriteAllText(fileName, File.ReadAllText(fileName, encoding), new UTF8Encoding(false));
      }

但任何人请告诉我如何在C#.net中找到csv文件的编码。

2 个答案:

答案 0 :(得分:2)

有一个简单类的示例将检测编码here(它不只是检查BOM)。

答案 1 :(得分:0)

我建议使用 CharsetDetector/UTF-unknown 来查找 csv 文件的编码。这是一个用 C# 构建的字符集检测器 - .NET 5、.NET Core 2-3、.NET 标准 1-2 和 .NET 4+。

<块引用>

检测文件、流和其他字节的字符集。

<块引用>

此软件包基于 Ude,并且自第 2 版起也基于 uchardet,它们是 Mozilla Universal Charset Detector 的端口。

// Detect from File (NET standard 1.3+ or .NET 4+)
DetectionResult result = CharsetDetector.DetectFromFile("path/to/file.txt"); // or pass FileInfo

// Get the best Detection
DetectionDetail resultDetected = results.Detected;

// Get the alias of the found encoding
string encodingName = resultDetected.EncodingName;

// Get the System.Text.Encoding of the found encoding (can be null if not available)
Encoding encoding = resultDetected.Encoding;

另外,这里是一个 Python 字符编码检测器:Chardet: The Universal Character Encoding Detector