首页 > 代码库 > c#逐行分元素读取记事本txt数据写进数据库

c#逐行分元素读取记事本txt数据写进数据库

其实这里最关键的一个方法是 StreamReader类里的 ReadLine();这个方法可以逐行读取txt流里面的数据。写了个简单的demo,已经加上了详细的注释说明。

 
ok,好了,不废话,下面直接上代码
 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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格式,下面的是gb2312格式 
            ///StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default); 
   
            //SqlConnection conn = DatabaseConnection.GetConnected(); 
            //conn.Open(); 
            string strLine0 = sr.ReadLine(); 
            ///当行内需要重新分散元素的是时候,我注释掉以下代码,demo里,用“,”区分行元素,然后,用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 你的表名 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(); 
        }

c#逐行分元素读取记事本txt数据写进数据库