怎么用C#语言遍历文件里面的内容?
2个回答
2012-11-05
展开全部
可以使用流读取文件,下面是一个例子,你可以参考:
private static ManualResetEvent readEvent = new ManualResetEvent(false); //设置阻塞类
static void Main(string[] args)
{
string filePath = @"F:\学习\CNT\练习.txt";
FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read);//初始化流
byte[] buffer = new byte[2]; //缓冲读取的内容
statee st = new statee(); //用于异步读取时用的类
st.buffer = buffer;
st.FSS = fs;
fs.BeginRead(buffer, 0, 2, EndRead, st); //异步开始读
readEvent.WaitOne(); //阻塞
Console.WriteLine("read over ");
Console.ReadLine();
fs.Close();
}
class statee
{
public byte[] buffer = new byte[2]; //存储读取的类
public FileStream FSS = null; //存储读取的流
}
private static void EndRead(IAsyncResult ar)
{
statee sttt = (statee)ar.AsyncState; //得到传输对象的值
FileStream fss = sttt.FSS; //得到传输的流
fss.EndRead(ar); //结束流
Console.WriteLine(Encoding.ASCII.GetString(sttt.buffer)); //输出信息
readEvent.Set(); //程序继续运行
}
private static ManualResetEvent readEvent = new ManualResetEvent(false); //设置阻塞类
static void Main(string[] args)
{
string filePath = @"F:\学习\CNT\练习.txt";
FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read);//初始化流
byte[] buffer = new byte[2]; //缓冲读取的内容
statee st = new statee(); //用于异步读取时用的类
st.buffer = buffer;
st.FSS = fs;
fs.BeginRead(buffer, 0, 2, EndRead, st); //异步开始读
readEvent.WaitOne(); //阻塞
Console.WriteLine("read over ");
Console.ReadLine();
fs.Close();
}
class statee
{
public byte[] buffer = new byte[2]; //存储读取的类
public FileStream FSS = null; //存储读取的流
}
private static void EndRead(IAsyncResult ar)
{
statee sttt = (statee)ar.AsyncState; //得到传输对象的值
FileStream fss = sttt.FSS; //得到传输的流
fss.EndRead(ar); //结束流
Console.WriteLine(Encoding.ASCII.GetString(sttt.buffer)); //输出信息
readEvent.Set(); //程序继续运行
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询