Friday, April 3, 2009

FTP Upload/Download using C#

Here is a very simple method for uploading and downloading files from FTP server.
you need to have FTP Host Name and UserName and Password for Authentication credentials

Make a reference to System.Net

DownLoad:

//Filepath is the path to your local machine where you want to download the file
//Filename is the name of the file which you want to download from FTP Server
private void Download(string filePath, string fileName,string UserName,string Password)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(txtPath.Text + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(UserName,Password);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
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);
}

ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}


Upload:

//Filename is the file from your local machine to upload
private void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = FTPPath+ "/" + fileInf.Name; //FTPPath points to the directory on FTP Server where you want to upload file
FtpWebRequest reqFTP;

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(txtUserName.Text, txtpassword.Text);
reqFTP.KeepAlive = false;

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

reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error");
}
}

Hope this will be helpful to you. some of codes i have taken from Code Project