Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write MemoryStream to byte[] [duplicate]

Tags:

c#

stream

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

like image 959
Polaris Avatar asked Jan 21 '13 16:01

Polaris


People also ask

Does MemoryStream copy byte array?

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.

How do I get bytes from MemoryStream?

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.

How do I write a string to MemoryStream?

MemoryStream stringInMemoryStream = new MemoryStream(ASCIIEncoding. Default. GetBytes("Your string here")); The string will be loaded into the MemoryStream , and you can read from it.

How do I copy one stream to another in C#?

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.


1 Answers

How about:

byte[] bytes = fs.ToArray(); 
like image 171
Gabe Avatar answered Sep 28 '22 06:09

Gabe