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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…