Question

I have a problem copying data from MemoryStream into Request Stream.

var Request = (HttpWebRequest.Create(Url) as HttpWebRequest);
Request.Method = "PUT";
Stream RequestStream = Request.GetRequestStream();

// write to MemoryStream
var MemStream = new MemoryStream();
byte[] Test = Encoding.ASCII.GetBytes("test000\r\n");
MemStream.Write(Test, 0, Test.Length);

// test writing correctly
byte[] B = MemStream.ToArray();
System.Windows.Forms.MessageBox.Show(Encoding.ASCII.GetString(B)); // shows data correctly

// copy data to request stream(not working!)
MemStream.CopyTo(RequestStream);

// add new data to request stream(working)
byte[] Test1 = Encoding.ASCII.GetBytes("test111");
RequestStream.Write(Test1, 0, Test1.Length);

Sent to the server only "test111". Got any ideas?

Was it helpful?

Solution

Copy to copies the data from current position. so it fails to copy as position is at end. where as ToArray returns all data irrespective of position.

Copying begins at the current position in the current stream, and does not reset the position of the destination stream after the copy operation is complete.

Try this

MemStream.Position = 0;
MemStream.CopyTo(RequestStream);

Refer Stream.CopyTo for more info

OTHER TIPS

The position of the memstream is at the end. because of the MemStream.Write(Test, 0, Test.Length);

use:

// copy data to request stream(would work!)
MemStream.Position = 0;
MemStream.CopyTo(RequestStream);

Set MemoryStream object Position=0 and use CopyTo method

MemStream.Position = 0; MemStream.CopyTo(RequestStream);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top