如何在c#中阅读和部分显示文本文件 [英] how can I read and partialy display a text file in c#

查看:112
本文介绍了如何在c#中阅读和部分显示文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我的需求。



1

hjgdfghjfg

fsgfggfg

egteg

tghtreghre

wthweghretg

结束



2

hjgdfghjfg

fsgfggfg

egteg

tghtreghre

wthweghretg

end





3

hjgdfghjfg

fsgfggfg

egteg

tghtreghre

wthweghretg

结束



假设此数字大量od data.I有3个按钮,分别名为1,2,3。如果我点击1,1 upto ed下的数据应该显示在另一个window.only数据介于1和end之间shuld disply.like这些如果我clik 2 dat下2应该显示..我可以在c#中以局部方式显示文件吗?请帮助它非常紧急我找不到更好的方法

Here my needs.

1
hjgdfghjfg
fsgfggfg
egteg
tghtreghre
wthweghretg
end

2
hjgdfghjfg
fsgfggfg
egteg
tghtreghre
wthweghretg
end


3
hjgdfghjfg
fsgfggfg
egteg
tghtreghre
wthweghretg
end

Assume under this number large amount od data.I have 3 button named 1,2,3 respectively.if I click 1 the data under the 1 upto ed should display in another window.only data in between 1 and end shuld disply.like these if I clik 2 dat under 2 should display..how can i partialy display a file in c#?? plese help its very urgent i cant find a better way

推荐答案

如果我理解正确你要从1到1,从2到3或从3到1结束。

我不知道为什么,但我希望你想从1到2,从2到3或从3结束。



尽管如此,最简单的方法是只读取每一行,直到找到起始行,然后在读取文本文件的其余部分并返回该内容时。

所以类似这样:

If I understood you correctly you want to retrieve from 1 till end, from 2 till end or from 3 till end.
I don't know why but I would expect that you want from 1 to 2, from 2 to 3 or from 3 to end.

Nevertheless the simplest way how you can do this is to just read each line until you find your starting line and when you do then just read the rest of the text file and return that content.
So something like this:
private static string ReadPartialText(string filePath, string startingLine)
{
    using (var reader = new StreamReader(filePath))
    {
        bool startingLineFound = false;

        while (!startingLineFound && !reader.EndOfStream)
            startingLineFound = reader.ReadLine().Equals(startingLine);

        return (startingLineFound) ? reader.ReadToEnd() : string.Empty;
    }
}



您可以像这样使用它:


And you can use it like this:

string partialText = ReadPartialText("C:\\Sample.txt", "2");



另外,如果我误解了你并且你实际上想在1和2或2和3之间读取,在这种情况下,而不是使用 ReadToEnd 你会想要继续逐行阅读,找到起始行后你会将这些行添加到 StringBuilder 中,当你找到一个结束行时,你将返回 StringBuilder 的内容。


Also just in case I misunderstood you and you actually want to read between 1 and 2 or 2 and 3, etc. in that case instead of using ReadToEnd you will want to continue reading line by line, after you found the starting line you will add those lines into a StringBuilder and when you find an ending line then you will return the StringBuilder's content.


这篇关于如何在c#中阅读和部分显示文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆