title: C# convert byte[] containing a c-style string to string - NOT Encoding.GetString(byte[])
body: <p>stupid me tries to convert a byte-array received from an external source not unter my control to a string. (And yes, I do know about <code>Encoding.GetString(byte[])</code>.</p>
  
  <p>What I have so far:</p>
  
  <pre><code>void myfunc()
  {
      byte[] rawData = new byte[ 128 ];
  
      for( int i = 0; i &lt; rawData.Length; ++i )
      {
          rawData[ i ] = 0;
      }
  
      rawData[ 0 ] = (byte)'H';
      rawData[ 1 ] = (byte)'e';
      rawData[ 2 ] = (byte)'l';
      rawData[ 3 ] = (byte)'l';
      rawData[ 4 ] = (byte)'o';
  
  
      string asString = Encoding.UTF8.GetString( rawData, 0, rawData.Length );
  
      string asRealString = Encoding.UTF8.GetString( rawData );
  }
  </code></pre>
  
  <p>Both strings do contain the Hello part but also a lot of \0's afterwards - which is not the thing I expected. 
  The output from the debugger:
  asRealString = </p>
  
  <pre><code>"Hello\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
  </code></pre>
  
  <p>Is there any way that would geive me a string like "Hello" ?</p>
  
  <p>I did goolge,but all I got was <code>Encoding.GetString(byte[])</code> ...</p>
  
  <p><strong>EDIT</strong>: The creatin of the byte array is outside my scope! I do get it as part of a larger, C-Style struct. And there is no leading length of the string. 
  Also I was hoping there iss ome built in way to tdo it and I did not have to find the first \o and tehn convert knowing the length....</p>
  
  <p><strong>EDIT</strong>
  Here is what I used in the end:</p>
  
  <pre><code>private static string convertCString( byte[] buffer, int maxLength, Encoding targetEncoding )
  {
      int length = 0;
      int realMax = buffer.Length &lt; maxLength ? buffer.Length : maxLength;
  
      for( 
           ; 0 != buffer[length] &amp;&amp; length &lt; realMax
           ; ++length )
      {}
  
      return targetEncoding.GetString( buffer, 0, length );
  }
  </code></pre>