Search for patterns in System.IO.Stream

I get System IO streams from the source. I will continue to stream object only if it contains a string "MSTND".

I understand that there is little that can be done in the stream if I do not convert it to a string. String conversion is for substring only. But I do not want to do anything that takes a lot of time or space. How is time / space intensity converting from Stream to string just for substring matching?

The code I wrote 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 ;
}
+5
source share
2 answers

, , , , , .

, Read . , , , , . , .

private string StreamHasString (Stream vStream) {
  byte[] streamBytes = new byte[vStream.Length];

  int pos = 0;
  int len = (int)vStream.Length;
  while (pos < len) {
    int n = vStream.Read(streamBytes, pos, len - pos);
    pos += n;
  }

  string stringOfStream = Encoding.UTF32.GetString(streamBytes);
  if (stringOfStream.Contains("MSTND")) {
    return stringOfStream;
  } else {
    return null;
  }
}

:

string s = StreamHasString(vStream);
if (s != null) {
  // proceed
}
+3

All Articles