每次写文件的读取都要看一下自己写过的代码才可以写出来,尽管用的再多都还是不记得,写了一个文件读写的类给自己,把读写代码变成了3行!
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace del
{
class wasterFileRead
{
private string FilePath="";
private Queue<string> Readline = new Queue<string>();
public bool IsLastLine
{
get
{
if (linenum==0)
{
return false;
}
else
{
return true;
}
}
}
private int linenum = 0;
public wasterFileRead(string filep)
{
FilePath = filep;
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.Default);
string rl = "";
while((rl=sr.ReadLine())!=null)
{
Readline.Enqueue(rl);
linenum += 1;
}
sr.Close();
fs.Close();
}
public string filePath
{
get
{
return FilePath;
}
set
{
FilePath = filePath;
}
}
public string GetOneLine()
{
linenum -= 1;
return Readline.Dequeue();
}
}
}
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace del
{
class wasterFileRead
{
private string FilePath="";
private Queue<string> Readline = new Queue<string>();
public bool IsLastLine
{
get
{
if (linenum==0)
{
return false;
}
else
{
return true;
}
}
}
private int linenum = 0;
public wasterFileRead(string filep)
{
FilePath = filep;
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.Default);
string rl = "";
while((rl=sr.ReadLine())!=null)
{
Readline.Enqueue(rl);
linenum += 1;
}
sr.Close();
fs.Close();
}
public string filePath
{
get
{
return FilePath;
}
set
{
FilePath = filePath;
}
}
public string GetOneLine()
{
linenum -= 1;
return Readline.Dequeue();
}
}
}
用了这个类之后读取c盘a.txt就简化成了3行
wasterFileRead re = new wasterFileRead(@"c:/a.txt");
while (re.IsLastLine)
{
richTextBox1.AppendText(re.GetOneLine()+"\n");
}
while (re.IsLastLine)
{
richTextBox1.AppendText(re.GetOneLine()+"\n");
}
IsLastLine就是返回是否最后一行
GetOneLine()依次返回读取到的行
初始化的时候要带文件的位置的字符串参数。
转载于:https://blog.51cto.com/waster/85160