//=====================
//描述:读取TXT文件
//本例中向一个ListBox添加信息
//ListBox的名字为TxtListBox
//
//返回:void
//作者:Kunsa
//创建时间:2010.5.4
//状态:已完成
//修改:
//=====================
private void TxtRead(string filename)
{
FileStream fs = new FileStream(filename,FileMode.Open,FileAccess.Read);
StreamReader sr = new StreamReader(fs);
sr.BaseStream.Seek(0, SeekOrigin.Begin);//从开始读取
string str = sr.ReadLine();
this.TxtListBox.Items.Clear();//清空ListBox中的内容
while(str!=null)
{
this.TxtListBox.Items.Add(str);
str = sr.ReadLine();
}
sr.Close();
fs.Close();
}
//判断文本文件行数方法
/// <summary>
/// 获取文本文件的行数
/// </summary>
/// <param name="path">文本文件的路径</param>
/// <returns>行数</returns>
public int lineIndex(string path)
{
int Length = 0;
StreamReader FileStreamTemp = new StreamReader(path);
while ((FileStreamTemp.ReadLine()) != null)
{
Length++;
}
FileStreamTemp.Close();
return Length;
}
//逐行读取方法
private void ReadTXTLineByLine()
{
string path = "";
System.IO.StreamReader file = new System.IO.StreamReader(path);//创建文件流,path为文本文件路径
int counter = 0;
string line = "";
string output = "";
int lineLength = lineIndex(path);
for (int _i = 0; _i < lineLength; _i++)
{
if ((line = file.ReadLine()) != null)
{
output = line;
MessageBox.Show("第" + counter.ToString() + "行读取成功,内容:\n" + output);
}
if (_i == (lineLength - 1))
{
MessageBox.Show("文本已读取完毕");
}
}
}