简体   繁体   中英

How to encode a CSV File Import?

I have this code :

string ABSfilePath = "";

CsvFileReader reader = null;
ABSfilePath = Server.MapPath("/myfile.csv");

try
{
    reader = new CsvFileReader(ABSfilePath);

    CsvRow myRow = new CsvRow();
    while (reader.ReadRow(myRow))
    {
        Response.Write(myRow[0].ToString()+"<br />");
    }
}
catch (Exception err)
{
    Response.Write(err.Message);
}
finally
{
    if (reader != null)
        reader.Dispose();
}

but when I try to import my file myfile.csv , some chars are "uncorrectly" encoded, like :

STATUA DELLA LIBERT�

So, how can encode this? Thanks

reader = new CsvFileReader(ABSfilePath);

is the culprit. You should first open a StreamReader with the correct encoding (I suspect UTF-8),

StreamReader MyStreamReader = new StreamReader(ABSfilePath, System.Text.Encoding.WhateverYouNeed);

then do

reader = new CsvFileReader(MyStreamReader.BaseStream);

What happens in your case is that the encoding of the CSV and the encoding of your page (html) do not match... you either make sure that both use the same encoding OR you convert the encoding of the CSV on reading. I don't know which class/library you use CsvFileReader but the easiest way would be to open the CSV with the correct encoding for example with a StreamReader instead of ABSFilePath as parameter...

You are using a non-standard class, I'll guess that you use this one . It is poorly designed, it doesn't let you change the encoding in any way. You'll need to add a new constructor to fix that:

    public CsvFileWriter(string filename, Encoding encoding)
        : base(filename, encoding)
    {
    }

Now you can get it to read something else than just utf-8. Best one to start with is Encoding.Default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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