Download Files from FTP
Read and Download Files from FTP
//Code to read the documents that are in FTP
public string[] GetDirectory()
{
StringBuilder result = new StringBuilder();
FtpWebRequest requestDir = (FtpWebRequest)WebRequest.Create("ftp://IPAddress/");
requestDir.Method = WebRequestMethods.Ftp.ListDirectory;
requestDir.Credentials = new NetworkCredential("username", "password");
FtpWebResponse responseDir = (FtpWebResponse)requestDir.GetResponse();
StreamReader readerDir = new StreamReader(responseDir.GetResponseStream());
string line = readerDir.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = readerDir.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
responseDir.Close();
return result.ToString().Split('\n');
}
//Code to download the files by filename. (you can get filename using above method)
public bool Download(string FTPfileName, string LocalPathtobeDownload)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://IPAddress/"+FTPfileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential("username", "password");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
StreamWriter writer = new StreamWriter(LocalPathtobeDownload);
writer.Write(reader.ReadToEnd());
writer.Close();
reader.Close();
response.Close();
return true;
}
catch
{
return false;
}
}
0 comments: