其实这里最关键的一个方法是 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 34class="csharp keyword" style="margin: 0px !important; padding: 0px !important; outline: 0px !important; border-radius: 0px !important; border: 0px currentColor !important; left: auto !important; top: auto !important; width: auto !important; height: auto !important; text-align: left !important; right: auto !important; bottom: auto !important; color: #006699 !important; line-height: 1.1em !important; overflow: visible !important; font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace !important; font-size: 1em !important; font-style: normal !important; font-weight: bold !important; vertical-align: baseline !important; float: none !important; position: static !important; min-height: inherit !important; box-sizing: content-box !important; background-image: none !important;">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();
}