0

I'm trying to read the following csv file:

Column1,Column2,Column3
MyData1,MyData2,MyData3
MyData11,MyData22,MyData33

Before I had the file stored locally and I would read it into my object like this:

string path = myPath;

var content = File.ReadAllLines(path)
                    .Skip(1)
                    .Select(x => x.Split(','))
                    .Select(x => new MyObject
                    {
                        Column1= x[0],
                        Colum2= x[1],
                        Column3 = x[2]
                    });

This worked fine for me. However, I now have a requirement to use the file upload control to select a file and then read from the file selected. I have no idea how to accomplish the same thing above. Any ideas?

AspUser7724
  • 109
  • 2
  • 10
  • this is not that difficult.. have you at least tried a google search on FileUpload Control there are tons of working examples on doing this.. also is this a `WinForms || WebForms` App..? [FileUpload Class](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload%28v=vs.110%29.aspx) if you want to see how to parse a `.CSV` file also checkout my previous Post here [Parsing CSV File](http://stackoverflow.com/questions/24088989/how-to-read-csv-file-splitting-by-commas-except-if-its-part-of-a-field) – MethodMan Dec 04 '14 at 18:56
  • I hope you realize that once you allow the file to be uploaded, your code will have to take into account the possibility of bad data. Your code above, for example, will crash rather horribly if a line doesn't contain at least three columns, or if somebody uploads a file that isn't a CSV. – Jim Mischel Dec 04 '14 at 19:03
  • @JimMischel I do realize that thanks. I'm just in the prelimary stages of development. Once I can get the data out of the file I will worry about everything else. – AspUser7724 Dec 04 '14 at 19:17
  • @DJKRAZE I have searched google and I can't seem to find an example that reads from the selected file. I don't have the path of this file I need to bring it into memory and read the contents and then assign the contents to an object. I have yet to see an example doing this. – AspUser7724 Dec 04 '14 at 19:18
  • Looks like a duplicate of https://stackoverflow.com/questions/12457407/insert-csv-from-file-upload-control-directly-to-memory-stream-without-physical-p – dbc Dec 04 '14 at 19:51
  • Also, .Net has a built in CSV parser: http://stackoverflow.com/questions/3507498/reading-csv-file/3508572#3508572 – dbc Dec 04 '14 at 19:53

1 Answers1

0

it is we explained in this link. You can covert it to a data table as shown in the link. Creating a DataTable from CSV File

Community
  • 1
  • 1