fileupload to filestream

fileupload to filestream  using -'c#,,file-upload,stream,filestream'

I am in process of sending the file along with HttpWebRequest. My file will be from FileUpload UI. Here i need to convert the File Upload to filestream to send the stream along with HttpWebRequest. How do i convert the FileUpload to a filestream?

asked Sep 16, 2015 by ukohale
0 votes

3 Answers

0 votes

Since FileUpload.PostedFile.InputStream gives me Stream, I used the following code to convert it to byte array

public static byte[] ReadFully(Stream input)
    byte[] buffer = new byte[input.Length];
    //byte[] buffer = new byte[16 * 1024];
    using (MemoryStream ms = new MemoryStream())
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            ms.Write(buffer, 0, read);
        return ms.ToArray();
answered Sep 16, 2015 by yashwantpinge
0 votes

Might be better to pipe the input stream directly to the output stream:


This way, you are not caching the entire file in memory before re-transmission. For example, here is how you would write it to a FileStream:

FileUpload fu;  // Get the FileUpload object.
using (FileStream fs = File.OpenWrite("file.dat"))

If you wanted to write it directly to another web request, you could do the following:

FileUpload fu; // Get the FileUpload object for the current connection here.
HttpWebRequest hr;  // Set up your outgoing connection here.
using (Stream s = hr.GetRequestStream())

That will be more efficient, as you will be directly streaming the input file to the destination host, without first caching in memory or on disk.

answered Sep 16, 2015 by amit_cmps
0 votes

You can't convert a FileUpload into a FileStream. You can, however, get a MemoryStream from that FileUpload's PostedFile property. You can then use that MemoryStream to fill your HttpWebRequest.

answered Sep 16, 2015 by santosh soni