如何读取文件
try
{
FileStream fs = new FileStream("C:\\TZJJ.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader m_streamReader = new StreamReader(fs);
//用StreamReader类来读取文件
m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
//从数据流中读取每一行,只到文件的最后一行
string strLine = m_streamReader.ReadLine();
while (strLine != null)
{
if (this.textBox1.Text.Trim() == "")
{
this.textBox1.Text = strLine;
strLine = m_streamReader.ReadLine();
continue;
}
if (this.textBox2.Text.Trim() == "")
{
this.textBox2.Text = strLine;
strLine = m_streamReader.ReadLine();
continue;
}
if (this.textBox9.Text.Trim() == "")
{
this.textBox9.Text = strLine;
strLine = m_streamReader.ReadLine();
break;
}
}
m_streamReader.Close();
}
catch (Exception ee)
{
MessageBox.Show("错误:" + ee.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
第二种方法
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.rT1.Text = "";
FileStream fs1 = new FileStream("2.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs1);
string str1 = sr.ReadToEnd();
this.rT1.Text = str1;
sr.Close();
fs1.Close();
}
}
}
|
|