C#(VS 2008)的与文件操作相关的类FileStream、StreamReader等,他们封装好的函数不够方便对文本文件制定行进行操作。但是利用StreamReader类的ReadLine可以间接地实现这个操作。实现方法有很多种,这里列举一种网上很多朋友都熟知的方法。另外,从文本文件制定位置读取可以调用API函数实现(当然也有其他方式),具体方法如有需要可以索取。
//用ArrayList必须加这句;
using System.Collections;
//读文件;
//path 工作目录; fgf 分隔符;
public ArrayList readTxtFile(string path,string fgf)
{
if (!File.Exists(path))
{
Console.WriteLine("文件不存在!");
Console.WriteLine("按回车键退出!");
Console.ReadLine();
return null;
}
try
{
//读出一行文本,并临时存放在ArrayList中
StreamReader sr = new StreamReader(path, Encoding.GetEncoding("gb2312"));
string l;
ArrayList content = new ArrayList();
while((l = sr.ReadLine()) != null)
{
ArrayList row = new ArrayList();
l = l.Trim();
int length = l.Length;
int i = 0;
bool fgf_flag = false;
while(i < length)
{
string x = l[i].ToString();
i++;
if (x.Equals(fgf))
{
fgf_flag = true;
row.Add(l.Substring(0,i-1));
length = length-i+1;
i = 0;
}
}
if (!fgf_flag)
row.Add(l);
row.TrimToSize();
//将多行文本储存在ArrayList中,并返回;
content.Add(row);
}
sr.Close();
content.TrimToSize();
return content;
}
catch(IOException ex)
{
Console.WriteLine("读文件出错!请检查文件是否正确。");
Console.WriteLine(ex.ToString());
return null;
}
}
//写文件;
public void writeTxtFile(string path,string fgf,ArrayList a)
{
//保存文件已存在
if (File.Exists(path))
{
Console.WriteLine("文件已存在!是否覆盖(O)、追加(A)该文件?退出直接按回车键。");
string over_flag = Console.ReadLine().ToString().Trim();
//追加到文件末尾
if (over_flag.Equals("A")||over_flag.Equals("a"))
{
try
{
StreamWriter sw = new StreamWriter(path,true,Encoding.GetEncoding("gb2312"));
IEnumerator cIE = a.GetEnumerator();
while (cIE.MoveNext())
{
ArrayList row =(ArrayList)cIE.Current;
//读取文本行中的字符段,并输出文件
IEnumerator rIE = row.GetEnumerator();
int length = row.Count;
int i = 0;
while (rIE.MoveNext())
{
string st = rIE.Current.ToString();
if (i==length-1)
sw.Write(st);
else
sw.Write(st+fgf);
i++;
}
sw.WriteLine();
}
sw.Close();
Console.WriteLine("写文件完毕,按回车键退出。。。");
Console.ReadLine();
}
catch(IOException ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("写文件出错!请检查文件是否正确。按回车键退出。。。");
Console.ReadLine();
}
}
}
}