Click here to Skip to main content
16,017,788 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
void TextDateYukle()
{
    using (StreamReader sr = new StreamReader(File.Open("C:\\Tr500.txt", FileMode.Open)))
    {
      using (SqlConnection txtbaglan = new
      SqlConnection("server=.;database=erisimik;trusted_connection=true"))
      {
        txtbaglan.Open();
        string line = "";
        while ((line = sr.ReadLine()) != "")
        {
          string[] parts = line.Split(new string[] { " " }, StringSplitOptions.None);
           string cmdTxt = String.Format("INSERT INTO pdks(kod,il) VALUES ('{0}','{1}')", parts[0], parts[1])", parts[0], parts[1]);
          using (SqlCommand cmddd = new SqlCommand(cmdTxt, txtbaglan))
          {
            cmddd.ExecuteNonQuery();
          }
        }
      }
    }
  }


Exception : IndexOutOfRangeException was unhandled
Error : Index was outside the bounds of the array.

string cmdTxt = String.Format("INSERT INTO pdks(kod,il) VALUES ('{0}','{1}')", parts[0], parts[1]);


Txt file: (file name Tr500.txt)

01,Ankara
02,Istanbul
03,Izmir

Database table columns name:

Column 1: kod
Column 2: il

How can I import the data from the file into SQL DB.

What is the reason for the error I' getting?


Thanks for your help!
Posted
Updated 2-Dec-10 2:54am
v3
Comments
Manfred Rudolf Bihy 2-Dec-10 8:58am    
Added code tag, spelling and grammar.

1 solution

Hi mhrglbdn!

The reason for your error is in the usage of the split function.
The way you described it you need to split on a comma not on a space.
Try correcting your code like this:

line.Split(new string[] { "," }, StringSplitOptions.None);


Since you were splitting on a space there are not enough parts in your array.

Modification
Since I found another error I'll just show the complete procedure:
void TextDateYukle()
{
    using (StreamReader sr = new StreamReader(File.Open("C:\\Tr500.txt", FileMode.Open)))
    {
        using (SqlConnection txtbaglan = new SqlConnection("server=.;database=erisimik;trusted_connection=true"))
	{
	    txtbaglan.Open();
	    string line = "";
	    while ((line = sr.ReadLine()) != "")
	    {
	        string[] parts = line.Split(new string[] { "," }, StringSplitOptions.None);
	        string cmdTxt = String.Format("INSERT INTO pdks(kod,il) VALUES ('{0}','{1}')", parts[0], parts[1]);//", parts[0], parts[1]);
                using (SqlCommand cmddd = new SqlCommand(cmdTxt, txtbaglan))
                {
                     cmddd.ExecuteNonQuery();
		}
            }
        }
    }
}

End Modification

Cheers


Manfred
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900