Possible Duplicate:
Creating a byte array from a stream
I'm trying to create text file in memory and write it byte[]
. How can I do this?
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; }
But it does not work because of data length
From expirience I can say, that it does not copy the array. Be aware though, that you are unable to resize the memory stream, when using an array in the constructor.
To get the entire buffer, use the GetBuffer method. This method returns a copy of the contents of the MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned.
MemoryStream stringInMemoryStream = new MemoryStream(ASCIIEncoding. Default. GetBytes("Your string here")); The string will be loaded into the MemoryStream , and you can read from it.
Stream.CopyToAsync Method (System.IO) Asynchronously reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.
How about:
byte[] bytes = fs.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With