简体   繁体   中英

How to read all lines of an csv file from HttpContent in C#

I want to create somo c# objects from an excel file read in from form data. It works if I first store it as a file and then use:

File.ReadAllLines(filename)
                   .Skip(1)
                   .Select(x => x.Split(','))...

However, I want to read it straight off the Stream from the HttpContent. When I try this, I get encoding issues.

    private const int WIN_1252_CP = 1252; // Windows ANSI codepage 1252    

    public IEnumerable<string> ReadLines(Func<Stream> streamProvider,
                                 Encoding encoding)
    {
        using (var stream = streamProvider())
        using (var reader = new StreamReader(stream, encoding))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                   yield return line;

            }
        }
    }

In web api action:

       ... 
       HttpContent file1 = files[0];

       Stream input = await file1.ReadAsStreamAsync();
       var listData = ReadLines(() => input,
                 Encoding.GetEncoding(WIN_1252_CP)).ToList();

I get the correct number of lines, but the encoding does not work.

Edit: In hindsight, I was being foolish and this would have worked with the utf-8 encoding. However, the answer gives a tidier way of implementing this functionality, so I hope it will still be useful

Similar to how it was read from the saved file use ReadAsStringAsync on the http content and then split by new line? That would be equivalent to file read all lines.

HttpContent file1 = files[0];
var input = await file1.ReadAsStringAsync();
var data = input.Split(Environment.NewLine)
                .Skip(1)
                .Select(x => x.Split(','))... 

The framework will take care of what ever encoding needs to be handled from the stream so that it is no longer a concern of the developer.

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