C# - 为什么StreamReader ReadLine在调用ReadLine之前读取数据?

时间:2017-08-07 07:43:20

标签: c# tcpclient streamreader

我使用StreamReader而不是NetworkStream,我想只读一行或多行,另一个数据是byte array(就像文件数据一样),我不想读取该文件数据StreamReader,例如我需要逐行读取文本标题,当我看到一个空行时,标题读取必须结束,然后我必须读取文件的字节, 当我使用StreamReader对此进行测试时,我遇到问题,因为StreamReader在调用ReadLine之前(先发送ReadLine之后)和处理StreamReader并使用{{{}之后读取了字节数1}}读取字节我得到的字节块在头之后不是文件字节数组的开头,因为NetworkStreamStreamReader中重写了字节块而没有调用ReadLine

StreamReader或我的代码设置有什么问题?

ReadLine

1 个答案:

答案 0 :(得分:3)

我创建了一个CustomStreamReader,并在ReadLine方法中逐个读取字节并解决了我的问题:

public class CustomStreamReader : Stream
{
    NetworkStream CurrentStream { get; set; }

    public CustomStreamReader(NetworkStream currentStream)
    {
        CurrentStream = currentStream;
    }

    public override bool CanRead => CurrentStream.CanRead;

    public override bool CanSeek => CurrentStream.CanSeek;

    public override bool CanWrite => CurrentStream.CanWrite;

    public override long Length => CurrentStream.Length;

    public override long Position { get => CurrentStream.Position; set => CurrentStream.Position = value; }

    public override void Flush()
    {
        CurrentStream.Flush();
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        return CurrentStream.Read(buffer, offset, count);
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        return CurrentStream.Seek(offset, origin);
    }

    public override void SetLength(long value)
    {
        CurrentStream.SetLength(value);
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        CurrentStream.Write(buffer, offset, count);
    }

    public string ReadLine()
    {
        List<byte> result = new List<byte>();
        do
        {
            int data = CurrentStream.ReadByte();
            if (data == -1)
                break;
            result.Add((byte)data);
            if (data == 13)
            {
                data = CurrentStream.ReadByte();
                if (data == -1)
                    break;
                result.Add((byte)data);
                if (data == 10)
                    break;
            }
        }
        while (true);
        return Encoding.UTF8.GetString(result.ToArray());
    }
}