C# 从特定位置读取文本文件到 EOF

发布于 2024-12-11 07:39:30 字数 349 浏览 0 评论 0原文

尝试找到一种好方法来读取文本文件并找到某个短语的最后一个实例,然后从该点读取文件到末尾。

简化的示例

sometext1...
sometext2...
[new]
sometext3...
[new]
sometext4...
sometext5...
[new]
sometext6...
sometext7...

“我想要返回”是写的最后一部分,

[new]
sometext6...
sometext7...

我可以想出方法来做到这一点,但我确信有一种非常有效的方法。 猜测必须找到“[new]”的最后一个索引并从那里读取。

Trying to find a good way to read a text file and find the last instance of a certain phrase and read the file to the end from that point.

example simplified

sometext1...
sometext2...
[new]
sometext3...
[new]
sometext4...
sometext5...
[new]
sometext6...
sometext7...

Want i want returned is the last part written

[new]
sometext6...
sometext7...

I can think of ways to do this, but i'm sure there is a very efficient way.
Guessing would have to find the last index of "[new]" and read from there.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

依 靠 2024-12-18 07:39:31

假设:

  1. [new] 始终独占一行。
  2. 没有一条线很大。
  3. 每个块都相当小(本身并不是一个巨大的内存负担)。
  4. 该文件可能非常大,因此您不想将整个文件读入内存。

然后我会做以下事情。改变前三个假设,事情会变得更棘手,改变第四个假设,我会很懒,只需将整个内容加载到:

using(TextReader tr = new StreamReader(filePath))
{
    StringBuilder sb = new StringBuilder();
    for(string line = tr.ReadLine(); line != null; line = tr.ReadLine())
        if(line == "[new]")
            sb = new StringBuilder("[new]");//flush last chunk read.
        else
            sb.Append('\n').Append(line);
    return sb.ToString();
}

Assuming:

  1. [new] is always on a line of its own.
  2. None of the lines are massive.
  3. Each chunk is reasonably small (not a massive memory burden in themselves).
  4. The file could be very large, so you don't want to read the whole thing into memory.

Then I would do the following. Change the first three assumptions and it gets trickier, change the fourth and I'd be lazy and just load the whole thing in:

using(TextReader tr = new StreamReader(filePath))
{
    StringBuilder sb = new StringBuilder();
    for(string line = tr.ReadLine(); line != null; line = tr.ReadLine())
        if(line == "[new]")
            sb = new StringBuilder("[new]");//flush last chunk read.
        else
            sb.Append('\n').Append(line);
    return sb.ToString();
}
我喜欢麦丽素 2024-12-18 07:39:31
var text =  File.ReadAllText(theFile);
var tail = text.SubString(text.LastIndexOf("[New]"));
var text =  File.ReadAllText(theFile);
var tail = text.SubString(text.LastIndexOf("[New]"));
情绪少女 2024-12-18 07:39:31

您可以打开一个文件流,将其包装到 TextReader 中,然后将 Position 属性的值保存在 FileStream 实例中。它允许您保存[新]代币的位置。

You can open a file stream, wrap it into TextReader, then save value of Position property in FileStream instance. It allows you to save positions of [new] tokens.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文