c#如何直接删除.txt的某一行数据,最好是有实例代码例如有1000行数据我只想删除800行 数据

剩余数据不要重新写入,直接保存就可以了

好像不能直接删除,但是是可以实现你要的功能,1000行用循环就可以了
用流打开,然后一行行地读,把你想要的行读入另外一个临时的文本,然后保存到当前文件就可以了
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-01-26
int lineno = 1; //删除行号
int highByte = 0; //判断换行符ASCII-13
int lowByte = 0; //判断换行符ASCII-10
long readCount = 0; //读取字节数
long startCount = 0; //删除行号起始字节数
long fileLength = 0; //文件长度
List<byte> buffer = new List<byte>();
using (FileStream fs = new FileStream("C:\\1.txt", FileMode.Open, FileAccess.ReadWrite))
{
fileLength = fs.Length;
while (lineno > -1) //扫描需要删除的行号
{
lowByte = fs.ReadByte();
if (highByte == 13 && lowByte == 10)
{
highByte = 0;
lineno--; //若遇到换行符则表示已经读取一行
if (lineno == 0)
startCount = readCount + 1;
}
if (lowByte == 13)
{
highByte = 13;
}
readCount++;
}
for (long i = readCount; i < fileLength; i++) //读取删除之后的文件内容
{
buffer.Add((byte)fs.ReadByte());
}
fileLength = fileLength - (readCount - startCount);
fs.SetLength(fileLength); //减小文件长度用于删除内容
fs.Position = startCount--;
byte[] write = buffer.ToArray();
fs.Write(write, 0, write.Length); //降删除行后的内容提前,即删除行
}本回答被网友采纳
相似回答