How to validate the text inside a .csv? I want to check the data and don’t save it, if at least 1 line of the file is incorrect.

Example data:

ISPROG3,09-23-14,BATMAN         #correct
ISPROG2,08-23-14,SUPERMAN       #correct
KRISTERKRISTEKRISTER            #wrong

My code:

        try
         { //this determines the type of extension that is only allowed in the fileupload
          string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
          string[] allowedExtenstions = new string[] { ".txt", ".csv"};
          if (allowedExtenstions.Contains(ext))
         { //if the extension is qualified then we proceed with the upload 
             string uploadfile = Server.MapPath("~/Upload/");//create first a folder where we will store the uploaded file
             uploadfile += FileUpload1.FileName;
             if (File.Exists(uploadfile))
             {
                 File.Delete(uploadfile);
             }
             FileUpload1.PostedFile.SaveAs(uploadfile);
             if (File.Exists(uploadfile))
             {
                 using (StreamReader sr = File.OpenText(uploadfile))// we read the file line by line
                 {
                     string inputline = "";
                     while ((inputline = sr.ReadLine()) != null)
                     {
                         string temp = inputline;
                         string name = temp.Substring(0, temp.IndexOf(","));//Name is from the first index [0] until the index of the first comma 
                         temp = temp.Substring(temp.IndexOf(",") + 1);// Only retain the date and feedbacks fields 
                         string date = temp.Substring(0, temp.IndexOf(","));//date is the start of the first index[0] until the index of the first comma
                         temp = temp.Substring(temp.IndexOf(",") + 1);//we cut the date and retain feedbacks
                         string feedbacks = temp;
                         upload.ID = int.Parse(txtID.Text);//it's in the textbox read-only
                         upload.Name = name;//upload.name comes from my business logic layer
                         upload.Date = date;//upload.date comes from my business logic layer
                         upload.Feedbacks = feedbacks;
                         upload.adduploads();//add function to transfer to the database
                         GridView2.DataSource = upload.search();//we view the added value 
                         GridView2.DataBind();

                     }
                 }

             }
         }
         else
         {
             Label39.Text = "NOTEPAD AND CSV FILE ONLY";
         }

        }
        catch (Exception ex)
        {
            Label39.Text = "*" + ex.Message;
       }

Related posts

Recent Viewed