FileUpload to FileStream

81,379

Solution 1

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();
    }
}

Solution 2

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

inputStream.CopyTo(outputStream);

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"))
{
    fu.PostedFile.InputStream.CopyTo(fs);
    fs.Flush();
}

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())
{
    fu.PostedFile.InputStream.CopyTo(s);
    s.Flush();
}

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.

Solution 3

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.

Solution 4

You can put a FileUpload file directly into a MemoryStream by using FileBytes (simplified answer from Tech Jerk)

using (MemoryStream ms = new MemoryStream(FileUpload1.FileBytes))
{
    //do stuff 
}

Or if you do not need a memoryStream

byte[] bin = FileUpload1.FileBytes;
Share:
81,379
Gopi
Author by

Gopi

!?!?!?!?

Updated on July 10, 2022

Comments

  • Gopi
    Gopi almost 2 years

    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?

  • ErikHeemskerk
    ErikHeemskerk about 12 years
    Once you access PostedFile, the file has already completely been buffered by ASP.NET. This can only be circumvented by using HttpRequest.GetBufferlessInputStream() (.NET 4 or higher), but that in turn requires you to parse the entire request body yourself.
  • PeterX
    PeterX over 10 years
    Could you please elaborate - possibly with a code example or link?
  • ErikHeemskerk
    ErikHeemskerk over 10 years
    @PeterX: See Extremeswank's answer for an example.