如何验证asp.net中上传文件中的文本

时间:2014-08-28 12:47:22

标签: c# asp.net

如何验证.csv内的文字?如果文件的至少1行不正确,我想检查数据并且不保存。

示例数据:

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

我的代码:

        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;
       }

1 个答案:

答案 0 :(得分:0)

你可以在你的行中计算逗号,如果这是唯一的问题并在if检查中使用它:

string temp = inputline;

bool saveFile = true;
// check for amount of comma in line
if(temp.Split(',').Length - 1 != 2) {
    saveFile = false;
}

if(saveFile) {
    // your save code     
}