从 StreamReader 获取剩余内容

发布于 2024-12-01 04:46:02 字数 527 浏览 0 评论 0原文

我有一个流读取器,用于从流中读取行。这很好用,但是我希望能够获得最后一行,该行永远不会以换行符结束,因此 readLine() 不会捕获它。

我将把它存储为一个全局变量,并在下次运行之前附加到流中。

这有可能吗?

void readHandler(IAsyncResult result)
{
    tcpClient = (TcpClient)result.AsyncState;
    StreamReader reader ;
    string line;
    using (reader = new StreamReader(stream))
    {
        while((line = reader.ReadLine()) != null){
            System.Diagnostics.Debug.Write(line);
            System.Diagnostics.Debug.Write("\n\n");
        }

    }
    getData();
}    

I have a stream reader that I am using to read lines from a stream. This works well however I would like to be able to get the last line which will never end with a line break so the readLine() will not capture it.

I will store this is a global variable and append to the stream before the next run.

Is this possible at all?

void readHandler(IAsyncResult result)
{
    tcpClient = (TcpClient)result.AsyncState;
    StreamReader reader ;
    string line;
    using (reader = new StreamReader(stream))
    {
        while((line = reader.ReadLine()) != null){
            System.Diagnostics.Debug.Write(line);
            System.Diagnostics.Debug.Write("\n\n");
        }

    }
    getData();
}    

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

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

发布评论

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

评论(2

晨敛清荷 2024-12-08 04:46:02

ReadLine 确实捕获流的最后一行,即使后面没有换行符。例如:

using System;
using System.IO;

class Test
{
    static void Main()
    {
        string text = "line1\r\nline2";

        using (TextReader reader = new StringReader(text))
        {
            string line;
            while((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

打印:

line1
line2

ReadLine()在到达流末尾并返回全部时返回null > 的数据。

ReadLine does capture the final line of the stream even if it doesn't have a line-break after it. For example:

using System;
using System.IO;

class Test
{
    static void Main()
    {
        string text = "line1\r\nline2";

        using (TextReader reader = new StringReader(text))
        {
            string line;
            while((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

Prints:

line1
line2

ReadLine() will only return null when it's reached the end of the stream and returned all of the data.

烟若柳尘 2024-12-08 04:46:02

除非您确实需要逐行执行此操作,否则您可以取消整个循环并仅使用 StreamReader.ReadToEnd 方法。这将为您提供当前缓冲区中的所有内容。

Unless you really need to do this line by line, you could do away with this entire loop and just use the StreamReader.ReadToEnd method. That will give you everything that's currently in the buffer.

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