If your script allows you to replace the original stream, you can check whether it supports the search and, if it does not read its contents, and transfers them to a new MemoryStream , which can then be used 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 quite inefficient, as it should allocate memory twice as much as your content. My recommendation would be to adapt the parts of your code where you access the stream (after reading all of its contents), so that you can access a saved copy of your content instead. For instance:
string content; using (var reader = new StreamReader(stream)) content = reader.ReadToEnd();
Since StringReader simply reads content from a string, you will not waste memory creating redundant copies of your data.
source share