将Txt文件转换成dataset
今天工作中,遇到需要将txt文件转化到内存表dataset中,于是写了一个方法来实现:
txt文件是特定格式的,文件中,一条记录为一行,各字段之间用“|”分割(注:最后一个字段后,有”|”)各字段依次为数据库中的相应字段。
举例如下:
ID号|线路编码|车站编码|运行模式|模式设置日期|模式设置时间
方法如下:
/**//// <summary>
/// 文件加载
/// </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;
}
/// 文件加载
/// </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];
}
http://www.cnblogs.com/winnxm/archive/2007/10/17/927880.html