Search code examples
c#csvmemorystream.net-standard-2.0iformfile

Convert uploaded .csv to memorystream and then to c# datatable in .Net Core


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.


Solution

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

    Encoding.UTF8.GetString(stream.ToArray());