2014-12-25 4 views
-4
다음

는 코드입니다 올바른 형식이 아닌 : 당신은 정수 유형의 세 필드가있는 DataTable을이입력 문자열은 C#에서 올바른 형식이 아니었다, int 값이

protected void Upload(object sender, EventArgs e) 
     { 
      if (FileUpload1.HasFile) 
      { 
       //Upload and save the file 
       string csvPath = Server.MapPath("~/App_Data/") + Path.GetFileName(FileUpload1.PostedFile.FileName); 
       FileUpload1.SaveAs(csvPath); 


      DataTable dt = new DataTable(); 
      dt.Columns.AddRange(new DataColumn[7] 
      { 
      new DataColumn("pataintno", typeof(int)), 
      new DataColumn("Firstname", typeof(string)), 
      new DataColumn("Lastname",typeof(string)), 
      new DataColumn("Age", typeof(int)), 
      new DataColumn("Address", typeof(string)), 
      new DataColumn("Email", typeof(string)), 
      new DataColumn("Phno", typeof(int)),}); 


      string csvData = File.ReadAllText(csvPath); 
      foreach (string row in csvData.Split('\n')) 
      { 
       if (!string.IsNullOrEmpty(row)) 
       { 
        dt.Rows.Add(); 
        int i = 0; 
        foreach (string cell in row.Split(',')) 
        { 
         dt.Rows[dt.Rows.Count - 1][i] = cell; 
         i++; 
        } 
       } 
      } 

      string consString = ConfigurationManager.ConnectionStrings["cnstr"].ConnectionString; 
      using (SqlConnection con = new SqlConnection(consString)) 
      { 
       using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con)) 
       { 
        //Set the database table name 
        sqlBulkCopy.DestinationTableName = "Pataint"; 
        con.Open(); 
        sqlBulkCopy.WriteToServer(dt); 
        con.Close(); 
        Array.ForEach(Directory.GetFiles((Server.MapPath("~/App_Data/"))), File.Delete); 
       } 
      } 
     } 
     else 
     { 
      Label1.Text = "PlZ TRY AGAIN"; 
     } 
    } 
+0

StackOverflow에 오신 것을 환영합니다. 귀하의 질문에 세부 사항을 추가하십시오, 마녀 줄에 오류가 있습니까? 그것을 해결하기 위해 어떤 노력을 했습니까? 너라면, 결과는 무엇일까요? – Sefa

+0

귀하의 질문은 무엇입니까? 문제가 무엇입니까? 너 뭐 해봤 니? – Sievajet

답변

0

코드를 확인한 결과 괜찮습니다. 난 당신이 CSV 파일을 확인하고 모든 열에 대한 헤더가 있는지 확인하는 것이 좋습니다.

1

오류가 말한다 파일에서 추출 된 하나 이상의 데이터가 유효한 정수가 아닙니다.

그래서 당신은 당신의 입력에 체크가 문자열을 정수로 변환 할 수없는 경우 false를 반환 것 Int32.TryParse를 사용하여 수행됩니다

// Read all lines and get back an array of the lines 
    string[] lines = File.ReadAllLines(csvPath); 

    // Loop over the lines and try to add them to the table 
    foreach (string row in lines) 
    { 
     // Discard if the line is just null, empty or all whitespaces 
     if (!string.IsNullOrWhiteSpace(row)) 
     { 
      string[] rowParts = row.Split(','); 

      // We expect the line to be splittes in 7 parts. 
      // If this is not the case then log the error and continue 
      if(rowParts.Length != 7) 
      { 
       // Log here the info on the incorrect line with some logging tool 
       continue; 
      } 

      // Check if the 3 values expected to be integers are really integers 
      int pataintno; 
      int age; 
      int phno; 

      if(!Int32.TryParse(rowParts[0], out pataintno)) 
      { 
       // It is not an integer, so log the error 
       // on this line and continue 
       continue; 
      } 
      if(!Int32.TryParse(rowParts[3], out age)) 
      { 
       // It is not an integer, so log the error 
       // on this line and continue 
       continue; 
      } 
      if(!Int32.TryParse(rowParts[6], out phno)) 
      { 
       // It is not an integer, so log the error 
       // on this line and continue 
       continue; 
      } 

      // OK, all is good now, try to create a new row, fill it and add to the 
      // Rows collection of the DataTable 
      DataRow dr = dt.NewRow(); 
      dr[0] = pataintno; 
      dr[1] = rowParts[1].ToString(); 
      dr[2] = rowParts[2].ToString(); 
      dr[3] = age 
      dr[4] = rowParts[4].ToString(); 
      dr[5] = rowParts[5].ToString(); 
      dr[6] = phno; 
      dt.Rows.Add(dr); 
     } 
    } 

(이러한 경우에 언제나처럼) 잘못된 입력을 확인해야합니다. 이 경우 어떤 종류의 오류 로그를 작성하여 루프가 완료되었는지 확인하고 어떤 행이 올바르지 않은지 확인하고 수정하십시오.

또한 코드를 변경 한 점에 유의하십시오. File.ReadAllLines을 사용하여 새 줄마다 문자를 입력 할 수 있습니다 (줄 바꿈이 \n 또는 \r\n 코드 인 경우 문제가 없음). 코드 패턴을 따라야하는 데이터 테이블에 새 행을 추가하려면 새 행을 만들고 값으로 채우고 기존 행에 새 행을 추가하십시오.

관련 문제