1

I am trying to make an application that will take in multiple file types and convert them to a c# DataTable. To do this I am first copying the file to a MemoryStream and recording the file's extension. Then based on the extension I need to read the stream in different ways.

I'm having difficulty when it comes to uploading a .csv file. I first copy it to a memory stream but then I am not being able to read from it correctly. Please help.

Example Code

public async Task<IActionResult> UploadFile(IFormFile file) {
    Datatable dt = new DataTable();
    var extension = Path.GetExtension(file.FileName);

    if (file.length > 0) {
        using (var ms = new MemoryStream()) {
            await file.CopyToAsync(ms);
            dt = ConvertFileToDataTable(ms, extension);
        }
    }
}

public DataTable ConvertFileToDataTable(MemoryStream stream, string ext) {
    switch (ext.ToLower()) {
        case ".xlsx":
            // Already have this working
            break;
        case ".csv":
            // This is where I need help
    }
}

With the CSV I am making the assumption that the first row contains the headers. If I could just convert the MemoryStream back into a csv string then I could handle the logic from there, I just don't know how to do that part.

The reason I need to do the conversion to a MemoryStream is because I'm working on a .Net Standard Library that wouldn't have access to IFormFile. It would take in the stream and return a data table. Basically, it handles the code in the method ConvertFileToDataTable above.

3
  • Have you tried: Encoding.UTF8.GetString(stream.ToArray()); Commented Dec 3, 2018 at 19:09
  • @RyanWilson That worked. Please enter that as an answer so that I can mark it correct. Commented Dec 3, 2018 at 19:16
  • Added as you requested. Commented Dec 3, 2018 at 19:33

1 Answer 1

3

You can get the byte array as a string by using:

Encoding.UTF8.GetString(stream.ToArray());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.