晕 导入文本导入不进去 求大神。
private void button1_Click(object sender, EventArgs e)
{
this.openFileDialog1.Filter = "文本文件(*.txt)|*.txt";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
string FileName = this.openFileDialog1.FileName;
char fenge = '-';
string strErrorMessage = "出错";
dataGridView1.DataSource = TxtToDataTable(FileName, fenge, ref strErrorMessage);
int count = dataGridView1.RowCount - 1;
lblCount.Text = "共导入" + count + "条数据";
// 你的 处理文件路径代码
}
}
public static DataTable TxtToDataTable(string strFileName, char strSplit, ref string strErrorMessage)
{
DataTable dtReturn = new DataTable();
try
{
string[] strFileTexts = File.ReadAllLines(strFileName);
if (strFileTexts.Length == 0)
{
strErrorMessage = "文件中没有数据!";
return null;
}
string[] strLineTexts = strFileTexts[0].Split('-');
if (strLineTexts.Length == 0)
{
strErrorMessage = "文件中数据格式不正确!";
return null;
}
//for (int i = 0; i < strLineTexts.Length; i++)
//{
// dtReturn.Columns.Add("Columns" + i.ToString());
//}
dtReturn.Columns.Add("账号");
dtReturn.Columns.Add("密码");
dtReturn.Columns.Add("注册状态");
for (int i = 0; i < strFileTexts.Length; i++)
{
strLineTexts = strFileTexts[i].Replace("----","-").Split('-');
DataRow dr = dtReturn.NewRow();
for (int j = 0; j < strLineTexts.Length; j++)
{
dr[j] = strLineTexts[j].ToString();
}
dtReturn.Rows.Add(dr);
}
}
catch (Exception ex)
{
strErrorMessage = "读入数据出错!" + ex.Message;
return null;
}
return dtReturn;
}