Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

How to upload and download files from a remote server in ASP.NET


View products that this article applies to.

INTRODUCTION

This article describes an All-In-One framework sample that is available for download. This code sample demonstrates how to upload and download files from a remote or local server in ASP.NET. You can download the sample packages from the following download icons. Both C# and Visual Basic .NET language versions of the sample package are available.


This code sample demonstrates how to upload and download files from a server that is not in the scope of the user’s request domain. Functionality is provided for transferring files with both the HTTP and FTP protocols. Also, this code sample uses Uniform Resource Identifiers (URIs) to identify the locations of files on a server. The key classes used in this code sample are the WebClient class and the WebRequest class.

Difficulty level


Download information

To download this code sample, click one of the following links:

Technical overview

It is fairly easy to upload and download files from a remote server in ASP.NET. The .NET Framework class library provides some lightweight request objects. The WebClient class is a high-level class that makes server interactions easier. WebRequest objects are used by the WebClient class to make requests. The HttpWebRequest and FtpWebRequest classes are protocol-specific implementations of the abstract WebRequest class. HttpWebRequest implements the GET and POST methods of the HTTP protocol to upload and download files. FtpWebRequest implements the STOR and RETR methods of the FTP protocol to upload and download files.


This code sample uses the UploadData and DownloadData methods of the WebClient class to transfer data to and from a remote server URI. The UploadData method is used with the HTTP protocol’s PUT method and the “application/x-www-form-urlencoded” Internet media type. The DownloadData method is used with a FileStream object to store the incoming data stream and write the byte array to a local file.

Sample overview

In this sample code, you will find the RemoteFileForm.aspx file that explains how to use the following two new classes: 

  • RemoteUpload
  • RemoteDownload

The RemoteUpload class

The RemoteUpload class has two child classes. These classes are HttpRemoteUpload and FtpRemoteUpload. Both classes use the RemoteUpload constructor. The RemoteUpload class requires a byte array of the file data and a server URI. You can also specify the name to use for the uploaded file. The FtpRemoteUpload class uses FtpWebRequest directly (instead of using the higher-level WebClient class) to handle the specific requirements of the FTP protocol.


See the following class definitions for more information about the RemoteUpload class:

public class HttpRemoteUpload : RemoteUpload
    {
        public HttpRemoteUpload(byte[] fileData, string fileNamePath, string urlString)
            : base(fileData, fileNamePath, urlString)
        {
 
        }
 
        public override bool UploadFile()
        {
            byte[] postData;
            try
            {
                postData = this.FileData;
                using (WebClient client = new WebClient())
                {
                    client.Credentials = CredentialCache.DefaultCredentials;
                    client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                    client.UploadData(this.UrlString, "PUT", postData);
                }
 
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to upload", ex.InnerException);
            }
 
        }
    }
 
 public class FtpRemoteUpload : RemoteUpload
    {
        public FtpRemoteUpload(byte[] fileData, string fileNamePath, string urlString)
            : base(fileData, fileNamePath, urlString)
        {
 
        }
 
        public override bool UploadFile()
        {
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(this.UrlString);
            reqFTP.KeepAlive = true;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = this.FileData.Length;
            
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            MemoryStream ms = new MemoryStream(this.FileData);
            
            try
            {
                int contenctLength;
                using (Stream strm = reqFTP.GetRequestStream())
                {
                    contenctLength = ms.Read(buff, 0, buffLength);
                    while (contenctLength > 0)
                    {
                        strm.Write(buff, 0, contenctLength);
                        contenctLength = ms.Read(buff, 0, buffLength);
                    }
                }
 
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to upload", ex.InnerException);
            }
        }
 
    } 

In the RemoteFileForm.cs file, when you click the Upload button, an instance of the RemoteUpload object is created. Pass the server URI and a local physical file path as parameters to create the object.


Note If you do not specify a file name to use to store the file on the server, the system will automatically generate a file name according to the current date and time on the server. The date and time is accurate to the millisecond. After the UploadData method finishes, the result is shown on the current page.

The RemoteDownload class

The RemoteDownload class also has two child classes. These classes are HttpRemoteDownload and FtpRemoteDownload. The RemoteDownload class requires a URI resource and a local physical directory. The RemoteDownload class checks to make sure that the URI resource exists before the download is started. The class retrieves the stream that contains the response data from the server, and then writes this byte array to a FileStream. The FtpRemoteDownload class uses FtpWebRequest directly (instead of using the higher-level WebClient class) to handle the specific requirements of the FTP protocol.


See the following class definitions for more information about the RemoteDownload class:

 public class HttpRemoteDownload : RemoteDownload
    {
        public HttpRemoteDownload(string urlString, string descFilePath)
            : base(urlString, descFilePath)
        {
 
        }
 
        public override bool DownloadFile()
        {
            string fileName = System.IO.Path.GetFileName(this.UrlString);
            string descFilePathAndName =
                System.IO.Path.Combine(this.DescFilePath, fileName);
            try
            {
                WebRequest myre = WebRequest.Create(this.UrlString);
            }
            catch
            {
                return false;
            }
            try
            {
                byte[] fileData;
                using (WebClient client = new WebClient())
                {
                    fileData = client.DownloadData(this.UrlString);
                }
                using (FileStream fs =
                      new FileStream(descFilePathAndName, FileMode.OpenOrCreate))
                {
                    fs.Write(fileData, 0, fileData.Length);
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("download field", ex.InnerException);
            }
        }
    }
 
public class FtpRemoteDownload : RemoteDownload
    {
        public FtpRemoteDownload(string urlString, string descFilePath)
            : base(urlString, descFilePath)
        {
 
        }
 
        public override bool DownloadFile()
        {
            FtpWebRequest reqFTP;
 
            string fileName = System.IO.Path.GetFileName(this.UrlString);
            string descFilePathAndName =
                System.IO.Path.Combine(this.DescFilePath, fileName);
 
            try
            {
 
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(this.UrlString);
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                
 
                using (FileStream outputStream = new FileStream(descFilePathAndName, FileMode.OpenOrCreate))
                using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse())
                using (Stream ftpStream = response.GetResponseStream())
                {
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                }
                return true;
            }
 
            catch (Exception ex)
            {
                throw new Exception("upload failed", ex.InnerException);
            }
        }
    } 


Note For more information about how to create and deploy the sample application, see the Readme.txt file that is included in the download package.
 

Languages

This code sample is available in the following programming languages:

Language Project Name
Visual C# CSRemoteUploadAndDownload
Visual Basic.NET VRemoteUploadAndDownload

Technology Category

  • ASP.NET 2.0
  • ASP.NET 3.5
  • ASP.NET 4.0

References

For more information about the WebClient class, visit the following Microsoft Developer (MSDN) website:

General information about the WebClient class

For more information about the UploadData method, visit the following MSDN website:

General information about the UploadData method

For more information about the DonwloadData method, visit the following MSDN website:

General information about the DonwloadData method

For more information about the FtpWebRequest method, visit the following MSDN website:

General information about the FtpWebRequest method

For more information about how to upload Files with FTP, visit the following MSDN website:

How to upload Files with FTP

↑ Back to the top


More Information

What is All-In-One Code Framework?

All-In-One Code Framework shows most Microsoft development techniques by using code samples in different programming languages. Each example is carefully selected, composed, and documented to show one common code scenario. For more information about All-In-One Code Framework, visit the following Microsoft website:

http://1code.codeplex.com

How to find more All-In-One Code Framework samples

To find more All-In-One Code Framework samples, search for "kbcodefx" together with related keywords on the Microsoft support Web site. Or, visit the following Microsoft website:

All-In-One Code Framework samples

↑ Back to the top


Rapid publishing disclaimer

Microsoft corporation and/or its respective suppliers make no representations about the suitability, reliability, or accuracy of the information and related graphics contained herein. All such information and related graphics are provided "as is" without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information and related graphics, including all implied warranties and conditions of merchantability, fitness for a particular purpose, workmanlike effort, title and non-infringement. You specifically agree that in no event shall Microsoft and/or its suppliers be liable for any direct, indirect, punitive, incidental, special, consequential damages or any damages whatsoever including, without limitation, damages for loss of use, data or profits, arising out of or in any way connected with the use of or inability to use the information and related graphics contained herein, whether based on contract, tort, negligence, strict liability or otherwise, even if Microsoft or any of its suppliers has been advised of the possibility of damages.

↑ Back to the top


Keywords: kbcodefx, kbinfo, kbnomt, kbsurveynew, kbrapidpub, atdownload, kb

↑ Back to the top

Article Info
Article ID : 2512241
Revision : 3
Created on : 4/17/2018
Published on : 4/17/2018
Exists online : False
Views : 380