I have the following code:
using (Stream responseStream = reply.GetResponseStream())
{
//Do not close the stream, this creates an error when saving a JPEG file
MemoryStream memoryStream = new MemoryStream();
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
When I used this in a console application, the file saved automatically to bin folder. Now I use it in a web application - and it is not saved at all.
How can I give a MemoryStream
a specific path so it will saved there, for example: "c:\\file.jpg"
?
I'm assuming reply
is an instance of HttpWebResponse
(via HttpWebRequest
).
Anyway, .NET 4 comes with Stream.CopyTo
which simplifies the process of copying from one stream to another without you needing to manually do it yourself with your own buffer.
Like so:
using( Stream responseStream = reply.GetResponseStream() )
using( Stream fileStream = new FileStream( @"C:\whatever\foo.bin", FileMode.CreateNew ) ) {
responseStream.CopyTo( fileStream );
}
That's it.