C# 读写文件的工具类

主要包含解析文件,读具体几行,向后插入行,重新覆盖文件等方法


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;

namespace pregnancy_autoupdate.utils
{
class TxtUtil
{
private int _LineNumber;
private string _FilePath;

///
/// 文件总行数
///

public int LineNumber
{
get{return this._LineNumber;}
}

///
/// 文件路径
///

public string FilePath
{
get{return this._FilePath;}
}

private ArrayList fileLine;

///
/// 读取文件到ArrayList里面去,按照行号排列
///

///
public TxtUtil(string FilePath)
{
this._FilePath = FilePath;
StreamReader sr = new StreamReader(new FileStream(FilePath, FileMode.OpenOrCreate), Encoding.GetEncoding("UTF-8"));
fileLine = new ArrayList();
int i = 0;
while (sr.Peek() > -1) {
fileLine.Insert(i,sr.ReadLine());
i = i + 1;

}
this._LineNumber = i;
sr.Close();
}

///
/// 返回某一行的内容
///

///
///
public string ReadLine(int LineIndex)
{
return this.fileLine[LineIndex].ToString();
}

public List readLastLineContent(int lastLineNumber)
{
List contents = new List();
int start = 0;
int end = this._LineNumber - 1;
if (lastLineNumber < this._LineNumber)
{
end = lastLineNumber - 1;

}
for (int i = start; i <= end; ++i)
{
contents.Add(ReadLine(i));
}
return contents;
}

///
/// 拿最后几行的数据,如果总行数不够,就拿文件的所有内容
///

public List readLastLineLogTxt(int lastLineNumber)
{
List logTxts = new List();
int start = this._LineNumber - 1;
int end = 0;
if (lastLineNumber < this._LineNumber)
{
end = this._LineNumber - lastLineNumber;

}
for (int i = start; i >= end; --i)
{
string content = ReadLine(i);
string[] ss = content.Split('#');
string logDate = ss[0];
string logConent = ss[1];

LogTxt logTxt = new LogTxt();
logTxt.LogDateTime = Convert.ToDateTime(logDate);
logTxt.LogContent = logConent;

logTxts.Add(logTxt);
}
return logTxts;
}


///
/// 插入某行到某处
///

public void InsertLine(int LineIndex, string LineValue)
{
if (LineIndex <= this._LineNumber)
{
this.fileLine.Insert(LineIndex, LineValue);
}
else
{
this.fileLine.Insert(this._LineNumber, LineValue);
this._LineNumber += 1;
}
}

///
/// 插入最后一行数据
///

public void InsertLine(string LineValue)
{
this.fileLine.Insert(this._LineNumber, LineValue);
this._LineNumber += 1;
}

///
/// 覆盖原文件
///

public void Save()
{
StreamWriter sw = new StreamWriter(this._FilePath);
for (int i = 0; i < this.fileLine.Count; i++)
{
sw.WriteLine(this.fileLine[i]);
}
sw.Close();
}


}
}


你可能感兴趣的:(C#)