Wednesday, 6 February 2013

CSV Helper Asp.Net MVC #4 Controller

Csv Helper Asp.Net MVC #4 Controller Razor.

In this tutorial we will focus on controller. We save file that user uploaded in our application and then csv reader helper will read the file and save data in our custom model.


Library that I used for this project : https://github.com/JoshClose/CsvHelper


5 comments:

  1. Hi,
    I'm having problems with this, I think I have exactly the same you show in the video, but when debugging, I can see AssetList (in your example ClientList) is empty, so it skip the loop. Any idea?

    This is the code in my controller:
    public ActionResult HandleCsv(HttpPostedFileBase fileUpload, int office)
    {
    string path = null;
    List fileContent = new List();

    try
    {
    if (fileUpload.ContentLength > 0)
    {
    var fileName = System.IO.Path.GetFileName(fileUpload.FileName);
    path = System.AppDomain.CurrentDomain.BaseDirectory + "Upload\\" + fileName;
    fileUpload.SaveAs(path);

    var csv = new CsvReader(new System.IO.StreamReader(path));
    var AssetList = csv.GetRecords();

    foreach (var a in AssetList)
    {
    objdb_Asset AssetsToDisplay = new objdb_Asset();
    AssetsToDisplay.Asset_Manufacturer = a.Manufacturer;
    AssetsToDisplay.Asset_Type = a.Type;
    [...]

    And this is my AssetInCsv class:

    public class AssetInCsv
    {
    public string PONumber;
    public string Type;
    public string Manufacturer;
    public string Model;
    public string Serial;
    }

    Thanks in advance!

    ReplyDelete
    Replies
    1. Wrong class, sorry, is this one:

      public class AssetInCsv
      {
      public string PONumber { get; set; }
      public string Type { get; set; }
      public string Manufacturer { get; set; }
      public string Model { get; set; }
      public string Serial { get; set; }
      }


      The exception message gives me this message:
      - $exception {"The reader has already exhausted all records. If you would like to iterate the records more than once, store the records in memory. i.e. Use CsvReader.GetRecords().ToList()"} System.Exception {CsvHelper.CsvReaderException}

      Delete
    2. I think the reason why you see an empty list is that when you hit break point before foreach loop, system will try to access csv class which is unaccessible as it has been stored in dll library. You can find out the original class here https://github.com/JoshClose/CsvHelper and copy it to you project and tell visual studio to use it when debugging next time.

      Have you tried to cast your object to list as compiler suggest?

      var AssetList = csv.GetRecords().ToList();


      Delete
  2. I followed your tutorial and it will not work. I insert a breakpoint and get o items in the container. I really want this to work.

    ReplyDelete