FileUpload to FileStream

前端 未结 4 1882
孤独总比滥情好
孤独总比滥情好 2020-11-30 06:48

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 al

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 07:26

    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.

提交回复
热议问题