其實這裡最關鍵的一個方法是 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 34public
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();
}