Upload a file using a stream

Source: Internet
Author: User

// Use the following method to upload files to any directory on the server

# Region private method save the file to the server SaveFile (system. Web. UI. webcontrols. fileupload, string savetourl)
/// <Summary>
/// Save the file to the server
/// </Summary>
/// <Param name = "fileupload"> upload Control </param>
/// <Param name = "savetourl"> Save path </param>
/// <Returns> check whether the file is successfully saved </returns>
Private bool SaveFile (system. Web. UI. webcontrols. fileupload, string savetourl)
{
Try
{
Filestream FS = new filestream (savetourl, filemode. openorcreate, fileaccess. Write );
FS. Write (this. getbyte (fileupload), 0, fileupload. postedfile. contentlength );
FS. Close ();

Return true;
}
Catch
{
Return false;
}
}
# Endregion

# Region private method to obtain the byte array getbyte (system. Web. UI. webcontrols. fileupload)
/// <Summary>
/// Obtain the byte array of the uploaded file
/// </Summary>
/// <Param name = "fileupload"> upload Control </param>
/// <Returns> Returns a byte array </returns>
Private byte [] getbyte (system. Web. UI. webcontrols. fileupload)
{// Obtain the converted byte array
// Get the file name to be uploaded
String strfilepathname = fileupload. postedfile. filename;
String strfilename = path. getfilename (strfilepathname );
Int filelength = fileupload. postedfile. contentlength;
// Upload a file
Byte [] filebytearray = new byte [filelength]; // temporary storage of byte Arrays for image files
Stream streamobject = fileupload. postedfile. inputstream; // create a data stream object
// Read image file data. filebytearray is the data storage body, 0 is the Data Pointer position, and filelne is the data length.
Streamobject. Read (filebytearray, 0, filelength );
Return filebytearray;
}
# Endregion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.