【问题标题】:How do I read a string of length n from StreamReader?如何从 StreamReader 读取长度为 n 的字符串?
【发布时间】:2020-04-23 15:52:24
【问题描述】:

我有一个StreamReader,我想读取下一个n 字节并将它们作为字符串返回。

只有一个 ReadLine() 方法返回一个字符串,但我的文件没有换行符 (CR/LF)。 Read() 改为返回 intReadBlock() 填充 char[]

有简单的方法吗?我应该使用Encoding.GetString() 吗?然后我需要读到byte[]

我发现编码和超过 1 个字节的字符存在问题,所以确切地说,我想读取 n 字节并且必须考虑编码。

【问题讨论】:

  • 这能回答你的问题吗? How do I convert StreamReader to a string?
  • 据我所知,它使用 ReadToEnd() 方法,所以我不这么认为,但谢谢。
  • 为什么你有/正在使用StreamReader?它用于读取文本文件。你不应该用它来读取二进制文件。此外,“我想读取n 字节并且必须考虑编码”似乎是矛盾的。要么你想读取基于编码的n字符,要么你想读取n忽略编码的字节。
  • 我正在阅读一个文本文件!我只是不想逐行阅读。我想读 n 个字符。假设每个字符是一个字节。

标签: c# .net string streamreader


【解决方案1】:

这应该会有所帮助:

private byte[] ReadPartial(Stream source, byte[] buffer, int start, int length)
{
    //the second parameter on the streamreader 
    //says that it should detect the encoding
    using(var reader = new StreamReader(source, true))
    {
        reader.BaseStream.Read(buffer, start, length);
    }
    return buffer;
}

【讨论】:

  • 谢谢,但这很奇怪,如果我通过“reader.BaseStream.Read(buffer, 0, 4)”从我的 StreamReader 中读取,即使 reader.ReadLine() 数组也只剩下零在同一个地方给了我一些文字(例如“1X 72X23”)。我究竟做错了什么?方法的结果 int 为 0,所以它没有读取我想的任何内容?
【解决方案2】:

这很有趣:

这不起作用(没有读数,m=0):

        byte[] buffer = new byte[4];
        int m = sr.BaseStream.Read(buffer, 0, 4);
        string s = sr.CurrentEncoding.GetString(buffer);

但确实如此:

        char[] cs= new char[4];
        sr.ReadBlock(inhalt, 0, 4);
        string s = new string(cs);

因此我认为使用 BaseStream 并不是一个好主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2013-12-22
    • 2013-01-23
    相关资源
    最近更新 更多