In this article I am going to discuss some helpful code snippets in C# to accomplish FTP File operations. I hope this will make your coding easier.
To connect to the FTP server we can use the FtpWebRequest C# object under the System.Net namespace.
Check whether file exists
private bool
FtpDirectoryExists(string Directory, string Username, string
Password)
{
//Directory = "ftp://" + FTPpath + "/"
+ Selectedfile;
FtpWebRequest fwr = (FtpWebRequest)WebRequest.Create(Directory);
FtpWebResponse fRes = default(FtpWebResponse);
fwr.Credentials = new NetworkCredential(Username, Password);
fwr.Method = WebRequestMethods.Ftp.GetFileSize;
try
{
fRes = (FtpWebResponse)fwr.GetResponse();
//no
error occured then the file is exists
return true;
}
catch (WebException
ex)
{
fRes = (FtpWebResponse)ex.Response;
//Error occured then the file doesn't
exists
if (FtpStatusCode.ActionNotTakenFileUnavailable
== fRes.StatusCode)
{
return false;
}
else
{
//Any other errors you need to handle
here
return false;
}
}
}
Listing all file Names
public DataTable
GetFTPFile(string Directory, string Username, string
Password)
{
DataTable dtFtpFileDetails = new DataTable();
dtFtpFileDetails.Columns.Add("FileName",
typeof(string));
try
{
//Get Directory Details
FtpWebRequest ftpClientdir;
ftpClientdir = (FtpWebRequest)FtpWebRequest.Create(Directory);
ftpClientdir.Credentials = new NetworkCredential(Username, Password);
ftpClientdir.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response =
ftpClientdir.GetResponse();
StreamReader
reader = new StreamReader(response.GetResponseStream());
//File names
FtpWebRequest ftpClient;
ftpClient = (FtpWebRequest)FtpWebRequest.Create(Directory);
ftpClient.Credentials = new NetworkCredential(Username, Password);
ftpClient.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response2 =
ftpClient.GetResponse();
StreamReader reader2 = new StreamReader(response2.GetResponseStream());
//read file/directory names into arraylist
string lsdirectory = reader2.ReadLine();
ArrayList lsnames = new ArrayList();
while (lsdirectory != null)
{
lsnames.Add(lsdirectory);
lsdirectory = reader2.ReadLine();
}
//read through directory details response
string line = reader.ReadLine();
while (line
!= null)
{
if (!line.StartsWith("d") && !line.EndsWith(".")) //"d"
= dir don't need "." or ".." dirs
{
foreach (String chk in lsnames) //compare basic
dir output to detail dir output to get dir name
{
if (line.EndsWith(chk))
{
DataRow dr = dtFtpFileDetails.NewRow();
dr["FileName"] = chk;
dtFtpFileDetails.Rows.Add(dr);
}
}
}
line = reader.ReadLine();
}
return dtFtpFileDetails;
}
catch (Exception)
{
return dtFtpFileDetails;
}
}
Download Files
public bool downloadfile(string Directory, string
Username, string Password, string Localpath, string
filename)
{
try
{
string localPath = Localpath + "\\";
FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(Directory
+ "/" + filename);
requestFileDownload.Credentials = new NetworkCredential(Username, Password);
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse responseFileDownload =
(FtpWebResponse)requestFileDownload.GetResponse();
Stream responseStream =
responseFileDownload.GetResponseStream();
FileStream writeStream = new FileStream(localPath
+ filename, FileMode.Create);
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead =
responseStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
}
responseStream.Close();
writeStream.Close();
requestFileDownload = null;
responseFileDownload = null;
return true;
}
catch (Exception
ex)
{
return false;
}
}
Upload File
private bool
UploadfiletoFTP(string LocalfilePath, string FileName, string
Directory, string Username, string Password)
{
try
{
FtpWebRequest
ftpClient = (FtpWebRequest)FtpWebRequest.Create(Directory + "/" + FileName);
ftpClient.Credentials = new System.Net.NetworkCredential(Username, Password);
ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftpClient.UseBinary = true;
ftpClient.KeepAlive = true;
System.IO.FileInfo fi = new System.IO.FileInfo(LocalfilePath
+ "/" + FileName);
ftpClient.ContentLength = fi.Length;
byte[] buffer = new
byte[4097];
int bytes = 0;
int total_bytes = (int)fi.Length;
System.IO.FileStream fs =
fi.OpenRead();
System.IO.Stream rs =
ftpClient.GetRequestStream();
while (total_bytes > 0)
{
bytes = fs.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
//fs.Flush();
fs.Close();
rs.Close();
FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
string value =
uploadResponse.StatusDescription;
uploadResponse.Close();
return true;
}
catch (Exception
ex)
{
return false;
}
}
Delete File
private bool
DeleteFtpFile(string Directory, string Username, string
Password, string Filename)
{
try
{
FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.Create(Directory
+ "/" + Filename);
requestFileDelete.Credentials = new NetworkCredential(Username, Password);
requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.GetResponse();
return true;
}
catch (Exception
ex)
{
return false;
}
}
References:
http://www.techrepublic.com/blog/how-do-i/how-do-i-use-c-to-upload-and-download-files-from-an-ftp-server/
http://khanrahim.wordpress.com/2010/09/03/file-download-upload-delete-in-ftp-location-using-c/