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

How to read Stream and reset its position to zero, even if stream.CanSeek == false ? I need a job.

+6
source share
2 answers

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(); // Process content here. string line; using (var reader = new StringReader(content)) while ((line = reader.ReadLine()) != null) Console.WriteLine(line); 

Since StringReader simply reads content from a string, you will not waste memory creating redundant copies of your data.

+9
source

Use another Stream implementation that supports search. If Stream.CanSeek returns false, then this implementation claims that it does not support search.

The MemoryStream object supports searching. You can copy an arbitrary stream to a MemoryStream using something like this, and the resulting stream will support the search, for example, you can reset the position to 0 and read it again.

 MemoryStream CopyStreamToMemory(Stream inputStream) { MemoryStream ret = new MemoryStream(); const int BUFFER_SIZE = 1024; byte[] buf = new byte[BUFFER_SIZE]; int bytesread = 0; while ((bytesread = inputStream.Read(buf, 0, BUFFER_SIZE)) > 0) ret.Write(buf, 0, bytesread); ret.Position = 0; return ret; } 

Of course, if your stream reads data that does not change, you can simply delete the old stream and create a new stream that reads the same data.

+5
source

Source: https://habr.com/ru/post/906584/


All Articles