zoukankan      html  css  js  c++  java
  • 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(); 
            }
  • 相关阅读:
    Elasticsearch 支持拼音自动补全
    laravel自动补全链接
    laravel的服务容器(药箱)、服务提供者(小盒子)、Facades(更方便用药),方便大家透彻理解
    php static静态属性和静态方法
    php面向对象的构造方法与析构方法
    MySQL事务-ROLLBACK,COMMIT用法详解
    php 事务处理transaction
    Python:初步学习Python
    iOS:自己写的一个星级评价的小Demo
    iOS:枚举enum的使用
  • 原文地址:https://www.cnblogs.com/gc2013/p/4155960.html
Copyright © 2011-2022 走看看