c#中的输入字符串格式不正确,int值格式不正确

时间:2022-10-22 11:34:02

Following is the code for it:

以下是它的代码:

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

2 个解决方案

#1


0  

I checked the code and it seems fine. I suggest you to check the csv file and make sure there are no headers for any columns.

我检查了代码,看起来很好。我建议你检查csv文件,确保没有任何列的标题。

#2


1  

You have a DataTable with 3 fields of type integer, the error says that one or more of the data extracted from your file are not valid integers.

你有一个包含3个整数类型字段的DataTable,错误表明从你的文件中提取的一个或多个数据都不是有效的整数。

So you need to check for bad input (as always in these cases)

所以你需要检查输入错误(在这些情况下一如既往)

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

The check on your input is done using Int32.TryParse that will return false if the string cannot be converted in an integer. In this case you should write some kind of error log to look at when the loop is completed and discover which lines are incorrect and fix them.

对输入的检查是使用Int32.TryParse完成的,如果字符串不能以整数转换,则返回false。在这种情况下,您应该编写某种错误日志来查看循环何时完成并发现哪些行不正确并修复它们。

Notice also that I have changed your code in some points: Use File.ReadAllLines so you have already your input splitted at each new line (without problem if the newline is just a \n or a \r\n code), also the code to add a new row to your datatable should follow the pattern: create a new row, fill it with values, add the new row to the existing collection.

另请注意,我在某些方面更改了您的代码:使用File.ReadAllLines,因此您已经在每个新行分割了您的输入(如果换行符只是\ n或\ r \ n代码,则没有问题),代码也是如此要向数据表添加新行,应遵循以下模式:创建新行,使用值填充新行,将新行添加到现有集合中。

#1


0  

I checked the code and it seems fine. I suggest you to check the csv file and make sure there are no headers for any columns.

我检查了代码,看起来很好。我建议你检查csv文件,确保没有任何列的标题。

#2


1  

You have a DataTable with 3 fields of type integer, the error says that one or more of the data extracted from your file are not valid integers.

你有一个包含3个整数类型字段的DataTable,错误表明从你的文件中提取的一个或多个数据都不是有效的整数。

So you need to check for bad input (as always in these cases)

所以你需要检查输入错误(在这些情况下一如既往)

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

The check on your input is done using Int32.TryParse that will return false if the string cannot be converted in an integer. In this case you should write some kind of error log to look at when the loop is completed and discover which lines are incorrect and fix them.

对输入的检查是使用Int32.TryParse完成的,如果字符串不能以整数转换,则返回false。在这种情况下,您应该编写某种错误日志来查看循环何时完成并发现哪些行不正确并修复它们。

Notice also that I have changed your code in some points: Use File.ReadAllLines so you have already your input splitted at each new line (without problem if the newline is just a \n or a \r\n code), also the code to add a new row to your datatable should follow the pattern: create a new row, fill it with values, add the new row to the existing collection.

另请注意,我在某些方面更改了您的代码:使用File.ReadAllLines,因此您已经在每个新行分割了您的输入(如果换行符只是\ n或\ r \ n代码,则没有问题),代码也是如此要向数据表添加新行,应遵循以下模式:创建新行,使用值填充新行,将新行添加到现有集合中。