How to read a Stream and reset its position to zero even if stream.CanSeek == false

后端 未结 2 999
南旧
南旧 2020-12-19 05:14

How do I read a Stream and reset its position to zero even if stream.CanSeek == false? I need some work around.

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-19 05:42

    If your scenario permits you to replace your original stream, then you could check whether it supports seeking and, if not, read its content and wrap them into a new MemoryStream, which you could then use for subsequent operations.

    static string PeekStream(ref Stream stream)
    {
        string content;
        var reader = new StreamReader(stream);
        content = reader.ReadToEnd();
    
        if (stream.CanSeek)
        {
            stream.Seek(0, SeekOrigin.Begin);
        }
        else
        {
            stream.Dispose();
            stream = new MemoryStream(Encoding.UTF8.GetBytes(content));
        }
    
        return content;
    }
    

    The above is rather inefficient, since it must allocate memory for twice the size of your content. My recommendation would be to adapt the parts of your code where you’re accessing the stream (after having read all its content) in order to make them access the stored copy of your content instead. For example:

    string content;
    using (var reader = new StreamReader(stream))
        content = reader.ReadToEnd();
    
    // Process content here.
    
    string line;
    using (var reader = new StringReader(content))
        while ((line = reader.ReadLine()) != null)
            Console.WriteLine(line);
    

    Since the StringReader just reads from your content string, you would not waste memory creating redundant copies of your data.

提交回复
热议问题