ASP.NET : C#: VB.NET : SQL Server : Oracle : Sharepoint : PHP : SSIS : SSRS : Wordpress : Plugins : Technology News

24 Aug 10 FTP Transfer: How to upload or download a file from ASP.NET Page

In one of my recent assignment I was asked to provide a way to end users to upload a file directly from web application. It was quite easy, code what I am providing here is just a snippet to show how to achieve this. This is written in C# and you will need to use System.Net and System.IO to use FTP and File operation.

Of course, you should have permission to upload/download a file to ftp server with proper credential and make sure you use “ftp://” instead of “http://” for the ftp server name. Along with this you may also need to catch all the errors you will encounter during the real implementation of ftp file transfer.

here is the code to upload a file, to download you need to use “DownloadFile” method in line 18.

protected void btnUpload_Click(object sender, EventArgs e)
FtpWebRequest myFtpWebRequest;
FtpWebResponse myFtpWebResponse;
StreamWriter myStreamWriter;
NetworkCredential myNetworkCredential;
StreamWriter myStream;
StreamReader myReadStream;

myFtpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(""));

myNetworkCredential = new NetworkCredential();

myNetworkCredential.UserName = "myusername";
myNetworkCredential.Password = "mypassword";
myFtpWebRequest.Credentials = myNetworkCredential;

myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
myFtpWebRequest.UseBinary = true;

myStream = new StreamWriter(myFtpWebRequest.GetRequestStream());

myStreamWriter = myStream;

myReadStream = new StreamReader((Server.MapPath("myTestFile.txt")));



myFtpWebResponse = (FtpWebResponse)myFtpWebRequest.GetResponse();

lblResponse.Text = myFtpWebResponse.StatusDescription;



If you use FileUpload Control (<asp:FileUpLoad /> ) for selecting files then it will not work for larger file unless you add one entry in web config file and here is what you need to add, length value should be in the rang of 0 and 2097151 (maximum file size, you will be able to upload with this setting). Default file size supported by FileUpload control is 4 MB.

    <httpRuntime maxRequestLength="2097151" executionTimeout="300"/>