C # Write the txt data in Notepad into the database by row-by-Row Element,
In fact, the most important method here is ReadLine () in the StreamReader class. This method can read the data in the txt stream row by row. I wrote a simple demo and added a detailed description.
OK, okay, no nonsense. Can I directly add the code below?
12345678910111213141516171819202122232425262728293031323334 |
public void InputData() { DataTable dt = new DataTable(); string strFilePath = "e:\\ouput1.txt" ; FileStream fs = new FileStream(strFilePath, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8); // UTF-8 format, the following is the gb2312 format ///StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default); //SqlConnection conn = DatabaseConnection.GetConnected(); //conn.Open(); string strLine0 = sr.ReadLine(); /// When the row needs to be re-dispersed, I will comment out the following code. In the demo, I will use the "," area branch element, and then insert it into the database with ado.net. /* String strLine1 = sr.ReadLine(); String strLine2 = sr.ReadLine();*/ while (strLine0 != null ) { string [] strArray = new string [4]; strArray = strLine0.Split( ',' ); DataRow dr = dt.NewRow(); dr[0] = strArray[0]; dr[1] = strArray[1]; dr[2] = strArray[2]; dr[3] = strArray[3]; // String SQL = "insert into your table name values ('" + dr [0] + "', '" + dr [1] + "', '"+ dr [2] +"', '"+ dr [3] + "')"; //SqlCommand cmd = new SqlCommand(sql, conn); //cmd.ExecuteNonQuery(); dt.Rows.Add(dr); strLine0 = sr.ReadLine(); } sr.Close(); fs.Close(); //conn.Close(); } |