繁体   English   中英

使用 CSVHelper 读取 ANSII 编码的 CSV 文件时出现问题

[英]Problem reading ANSII Encoded CSV file with CSVHelper

我正在使用 CSVHelper 读取 CSV 文件,其中包含一些字符,例如 GBP 字符(例如 £2000)

但是,在处理文件时,磅符号会丢失,而是出现带有问号的菱形。

我的代码如下:

        var csvConfig = new CsvConfiguration(new CultureInfo("en-GB"))
        {
            ShouldSkipRecord = (row) =>
            {
                if (row.Row.Parser.Row <= 4)
                {
                    return true;
                } else
                {
                    return false;
                }                    
            }
        };

        using var streamReader = File.OpenText(_fileName);
        using var csvReader = new CsvReader(streamReader, csvConfig);
        
        var records = csvReader.GetRecords<WebApi.Entities.Csv.Transaction();

        foreach (var record in records)
        {
            System.Diagnostics.Debug.WriteLine(record.PaidIn);
        }

上面的代码输出包含带有菱形问号的井号的字段。例如:?2000

在处理之前,我无法将源文件转换为 UTF-8。 但是,我尝试在上面的 function 中将其转换为 UTF-8 并且没有用。

我迷路了,需要一些指导。

- - 更新 - - - - - - - - - - - - - - - - -

阅读评论后,我按照建议进行了检测文件的编码,然后传递给 StreamReader:

    var csvConfig = new CsvConfiguration(new CultureInfo("en-GB"))
    {
        ShouldSkipRecord = (row) =>
        {
            if (row.Row.Parser.Row <= 4)
            {
                return true;
            } else
            {
                return false;
            }                    
        }
    };

    //get current encoding of source csv file
    var reader = new StreamReader(_fileName, Encoding.Default, true);
    if (reader.Peek() >= 0)
        reader.Read();
    Encoding encoding = reader.CurrentEncoding;

    using var streamReader = new StreamReader(_fileName, reader.CurrentEncoding);
    using var csvReader = new CsvReader(streamReader, csvConfig);
    
    var records = csvReader.GetRecords<WebApi.Entities.Csv.Transaction>();

    foreach (var record in records)
    {
        System.Diagnostics.Debug.WriteLine(record.PaidIn);
    }

但这一切都在脉络中,这仍然没有解决原来的问题。

最后,尝试检测当前文件的编码导致 .NET 返回正确的编码,因此我手动指定了编码:

using var streamReader = new StreamReader(_fileName, Encoding.GetEncoding("iso-8859-1"));

以上解决了我的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM