在文本文件中寻找一行 [英] Seeking for a line i a text file
本文介绍了在文本文件中寻找一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一些帮助,我正在编写一个读取文本文件的方法,如果发生任何异常,我会在文本文件中附加一行.例如**"
I need some assistance, I am writing a method to read a text file, and if any exception occurs I append a line to the text file. e.g "**"
所以我需要知道的是如何在不读取文本文件的每一行的情况下检查文本文件中的特定文本行,例如 peek 方法或其他什么.
So what I need to know is how can I check for that specific line of text in the text file without reading every line of the text file, like a peek method or something.
任何帮助将不胜感激.
提前致谢.
推荐答案
我找到了一个解决方案,我附加到文件中的那一行永远是文件的最后一行,所以我创建了一个方法来读取最后一行线.见下文:
I have found a solution, the line I have appended to the file will always be the last line in the file, so I created a method to read the last line. See below:
public string ReadLastLine(string path)
{
string returnValue = "";
FileStream fs = new FileStream(path, FileMode.Open);
for (long pos = fs.Length - 2; pos > 0; --pos)
{
fs.Seek(pos, SeekOrigin.Begin);
StreamReader ts = new StreamReader(fs);
returnValue = ts.ReadToEnd();
int eol = returnValue .IndexOf("\n");
if (eol >= 0)
{
fs.Close();
return returnValue .Substring(eol + 1);
}
}
fs.Close();
return returnValue ;
}
这篇关于在文本文件中寻找一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文