public static DataSet TextFileLoader(string FilePath, string TableName, string[] FieldsInArray)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable(TableName);
StreamReader sr = new StreamReader(FilePath, System.Text.Encoding.GetEncoding("GB2312"));
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');
aryVale = strRead.Split('|');
DataRow dr = dt.NewRow();
for (int k = 0; k < aryVale.Length; k++)
{
dr[FieldsInArray[k]] = aryVale[k].ToString();
}
dt.Rows.Add(dr);
}
else
{
flag = false;
}
}
ds.Tables.Add(dt);
return ds;
}
{
DataSet ds = new DataSet();
DataTable dt = new DataTable(TableName);
StreamReader sr = new StreamReader(FilePath, System.Text.Encoding.GetEncoding("GB2312"));
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');
aryVale = strRead.Split('|');
DataRow dr = dt.NewRow();
for (int k = 0; k < aryVale.Length; k++)
{
dr[FieldsInArray[k]] = aryVale[k].ToString();
}
dt.Rows.Add(dr);
}
else
{
flag = false;
}
}
ds.Tables.Add(dt);
return ds;
}
TextFileLoader(string FilePath, string TableName, string[] FieldsInArray)方法是返回读取文件的结果集;
Page_Load中的操作如下:
string[] FieldsInArray = { "IP1", "IP2", "Prov", "City"};
DataSet ds = new DataSet();
ds = TextFileLoader(@"E:\IPAddr.txt", "good", FieldsInArray);
Hashtable hs = new Hashtable();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string sql = "INSERT INTO [IPAddr] ( [IP1],[IP2], [Prov], [City]) VALUES ( '" + ds.Tables[0].Rows[i]["IP1"] + "','" + ds.Tables[0].Rows[i]["IP2"] + "', '" + ds.Tables[0].Rows[i]["Prov"] + "','" + ds.Tables[0].Rows[i]["City"] + "') ";
hs.Add(i, sql);
}
Hashtable ht = hs;
bool fla=ExecuteSqlTran(hs);
if (fla)
{
Response.Write("数据添加成功");
}
else
{
Response.Write("数据添加出现异常");
}
DataSet ds = new DataSet();
ds = TextFileLoader(@"E:\IPAddr.txt", "good", FieldsInArray);
Hashtable hs = new Hashtable();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string sql = "INSERT INTO [IPAddr] ( [IP1],[IP2], [Prov], [City]) VALUES ( '" + ds.Tables[0].Rows[i]["IP1"] + "','" + ds.Tables[0].Rows[i]["IP2"] + "', '" + ds.Tables[0].Rows[i]["Prov"] + "','" + ds.Tables[0].Rows[i]["City"] + "') ";
hs.Add(i, sql);
}
Hashtable ht = hs;
bool fla=ExecuteSqlTran(hs);
if (fla)
{
Response.Write("数据添加成功");
}
else
{
Response.Write("数据添加出现异常");
}