Loading a list of files from ftp to a local folder using C #?
I am looking to download all files in ftp to my local folder. All files should be deleted in ftp after uploading to local disk.
From below code
-
I can only download a file from ftp where I do not expect
-
I need to put all files in a folder, but not in the name of the local file name.
My code:
using (WebClient ftpClient = new WebClient())
{
ftpClient.Credentials = new System.Net.NetworkCredential("ftpusername", "ftp pass");
ftpClient.DownloadFile("ftp://ftpdetails.com/dec.docx",@"D:\\Mainfolder\test.docx");
}
From the above code, I can download the file and only put it in the filename. Where I have so many files to download from ftp and put it in a local folder. All suggestions are greatly appreciated.
source to share
Here's an example using FTPWebResponse to get a list of filenames from a directory:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.funet.fi/pub/standards/RFC/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
String filename = reader.ReadLine();
Console.WriteLine(filename);
//you now have the file name, you can use it to download this specific file
}
Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
}
}
}
Then you can use this list to download each file. Note that if you have a lot of files to upload, you might want to look into asynchronous uploads to speed things up, but I would get this working before trying to implement any asynchronous stuff.
source to share
I don't think WebClient is a valid FTP client. Use the standard FtpWebRequest and FtpWebResponse classes instead .
If not, there are several free C # ftp clients that will do the job.
source to share