I am attempting to send files to a request by writing them to the response object.
I currently have two ways. The first way (using FileStream
) works and the second way(using MemoryStream
) fails. I would like to know why the second way fails as I do not want to create a filestream all the time. Following is the code
//This method does not work
MemoryStream ms = MethodA(bundleStream);
ms.CopyTo(Context.Response.Body); //<---Copy memory stream to response (Fails - object at other end is empty)
The other method works. In this method I basically write to a file and then reopen that written file and copy to the 'Context.Response.Body'
//This method works.
MemoryStream ms = MethodB(bundleStream,"C:\\Mytestfile.exe"); //Wrtie to Mytestfile.exe
ftest = new FileStream("C:\\Mytestfile.exe", FileMode.Open); //Now open the same file that was written
ftest.CopyTo(Context.Response.Body); <---Copy file stream to response (Works)
ftest.Close();
I wanted to know why the first method fails. Apparently when I read the incoming response its empty while I can easily read the response when the second method is used.
You need to reset the position of the memory stream before copying it to the request stream.
ms.Seek(0, SeekOrigin.Begin);