怎样按行读取文本文件中的行(除第一行和最后一行)
private DataTable ReadTextFile(string FileName)
{
try
{
string[] strText = System.IO.File.ReadAllLines(FileName);
if (strText.Length > 0)
{
DataTable dtData = new DataTable();
for (int intIdx = 0; intIdx < strText.Length - 1; intIdx++)//strText.Length - 1去掉了最后一行
{
string[] strLine = strText[intIdx].Split(',');
if (intIdx == 0)
{
//由于第一行不要,此处只用来创建表结构,添加列
for (int intText = 0; intText < strLine.Length; intText++)
{
dtData.Columns.Add("C" + intText.ToString().PadLeft(4, '0'));
}
}
else
{
//若要第一行,只需去掉[else]
DataRow drRow = dtData.NewRow();
for (int intText = 0; intText < strLine.Length; intText++)
{
drRow[intText] = strLine[intText];//intText赋值
}
dtData.Rows.Add(drRow);
}
}
return dtData;
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
} |
|