Pattern search in a System.IO.Stream

c#, stream

Solution

Depending on where in the stream you're expecting this sequence it would be fairly efficient to convert to a string to perform the substring. If its in a standard spot each time then you can read through the number of bytes required and convert them to a string.

Take a look at this for some reference: http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx

Alternatively you could convert the string "MSTND" to a byte[] and search the stream for the byte[].

Edit:

I found How do I get a consistent byte representation of strings in C# without manually specifying an encoding? which should help with converting the string to byte[].

Problem

I am receiving System IO Streams from a source. I will proceed with the stream object only if it contains the string `"MSTND"`. I realize there is not much I can do on the stream unless I convert it into string. The string conversion is only for sub-string matching. But I don't want to do anything that takes up lot of time or space. How time / space intensive is a conversion from Stream to string just for sub-string matching? The code I have written is: ``` private bool StreamHasString (Stream vStream) { bool containsStr = false; byte[] streamBytes = new byte[vStream.Length]; vStream.Read( streamBytes, 0, (int) vStream.Length); string stringOfStream = Encoding.UTF32.GetString(streamBytes); if (stringOfStream.Contains("MSTND")) { containsStr = true; } return containsStr ; } ```

Original source

Related problems