举例如下:
ID号|线路编码|车站编码|运行模式|模式设置日期|模式设置时间
1|98|9821|06|20070913|211835|
方法如下:
/// 文件加载
/// </summary>
/// <param name="FilePath">带文件名的路径</param>
/// <param name="TableName">自定义的表名</param>
/// <param name="FieldsInArray">自定义的表字段</param>
/// <returns>DataSet</returns>
public static DataSet TextFileLoader(string FilePath, string TableName, string[] FieldsInArray)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable(TableName);
FileStream fs = File.Open(FilePath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
for (int i = 0; i < FieldsInArray.Length; i++)
{
dt.Columns.Add(new DataColumn(FieldsInArray[i], typeof(string)));
}
string strRead;
bool flag = true;
while (flag)
{
strRead = sr.ReadLine();
if (!string.IsNullOrEmpty(strRead))
{
string[] aryVale = strRead.Split('\t');
DataRow dr = dt.NewRow();
for (int k = 0; k < aryVale.Length; k++)
{
dr[FieldsInArray[k]] = aryVale[k];
}
dt.Rows.Add(dr);
}
else
{
flag = false;
}
}
ds.Tables.Add(dt);
return ds;
}
private void button2_Click(object sender, EventArgs e)
{
string[] FieldsInArray ={ "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7" };
DataSet ds = new DataSet();
ds =TextFileLoader(@"D:\cpbuyaa20071018.txt","good",FieldsInArray);
dataGridView1.DataSource = ds.Tables[0];
}