title: How can I write MemoryStream to byte[]
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream">Creating a byte array from a stream</a>  </p>
  </blockquote>
  
  
  
  <p>I'm trying to create text file in memory and write it <code>byte[]</code>. How can I do this?</p>
  
  <pre><code>public byte[] GetBytes()
  {
      MemoryStream fs = new MemoryStream();
      TextWriter tx = new StreamWriter(fs);
  
      tx.WriteLine("1111");
      tx.WriteLine("2222");
      tx.WriteLine("3333");
  
      tx.Flush();
      fs.Flush();
  
      byte[] bytes = new byte[fs.Length];
      fs.Read(bytes,0,fs.Length);
  
      return bytes;
  }
  </code></pre>
  
  <p>But it does not work because of data length</p>