//判断文本文件行数方法 ///
/// 获取文本文件的行数
///
/// 文本文件的路径
///
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("文本已读取完毕");
}
}
}
用IO文件流读取首先导入IO命名空间 using System.IO;FileStream myfs = new FileStream("你的文件路径", FileMode.Open);
StreamReader mySr = new StreamReader(myfs);
mySr.Read();这个方法一次读取一行
mySr.Close();
myfs.Close();
//打开文件
private void 打开OToolStripMenuItem_Click(object sender, EventArgs e)
{
string path = null;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "我的记事本 -打开文件对话框";
ofd.Filter = "文本文件(*.txt)|*.txt";
ofd.AddExtension = true; //当文件扩展名被隐藏.对话框自动在文件命名中加入文件扩展名
ofd.DefaultExt = "*.txt"; //获取默认的文件名
if (ofd.ShowDialog() == DialogResult.OK)
{
path = ofd.FileName;
}
try
{
StreamReader sr = new StreamReader(path, Encoding.Default);
新建ToolStripMenuItem_Click(sender, e); //调用新建文件事件
this.richTextBox1.Text = sr.ReadToEnd();
sr.Close(); //关闭文件并释放资源 }
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
}