Importing CSV file in MVC and converting it in JSON using C#

609 views Asked by At

I am importing .CSV file from an angular app into MVC and i am able to get the files like this

Int32 strLen, strRead;
            System.IO.Stream stream = Request.InputStream;
            strLen = Convert.ToInt32(stream.Length);
            byte[] strArr = new byte[strLen];
            strRead = stream.Read(strArr, 0, strLen);

here the files which is being imported is converted into byte[] because i am reading the file using

System.IO.Stream stream = Request.InputStream

Then i convert it into string like this

 string a = System.Text.Encoding.UTF8.GetString(strArr);

and try to split the content and retrieve the data but it becomes very complex, i wonder if there is any alternate way for it. In a simple .CSV file like this

enter image description here I get the result after converting the byte[] to string like this

enter image description here

and once i apply logic for splitting the string and retrieving the data, the logic gets very messy like this

enter image description here

Is there any efficinet way where i can convert the imported .CSV file to JSON

2

There are 2 answers

4
kkost On

Save stream as text file in to the TEMP folder.

Use any parcer for working with CSV file. (Example FileHelpers)

Use any Json helper to convert it to the output format. (Example: newtonsoft)

0
Cinchoo On

You can use Cinchoo ETL - an open source library, to convert CSV to JSON easily.

using (var parser = new ChoCSVReader("IgnoreLineFile1.csv")
    .WithField("PolicyNumber", 1)
    .WithField("VinNumber", 2)
    .Configure(c => c.IgnoreEmptyLine = true)
    .Configure(c => c.ColumnCountStrict = true)
    )
{
    using (var writer = new ChoJSONWriter("ignoreLineFile1.json")
            .WithField("PolicyNumber", fieldName: "Policy Number")
            .WithField("VinNumber", fieldName: "Vin Number")
        )
        writer.Write(parser.Skip(1));
}

In above, you can pass stream to the reader and writer as well for your requirement.

Hope this will help.

Disclaimer: I'm the author of this library.