The easiest way
The easiest way to upload a file to an FTP server using the .NET Framework is to use the WebClient.UploadFile method :
WebClient client = new WebClient(); client.Credentials = new NetworkCredential("username", "password"); client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
Advanced settings
If you need more control that WebClient does not offer (e.g. TLS / SSL encryption , ASCII mode, active mode, etc.), use FtpWebRequest . An easy way is to simply copy the FileStream to an FTP stream using Stream.CopyTo :
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Ftp.UploadFile; using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip")) using (Stream ftpStream = request.GetRequestStream()) { fileStream.CopyTo(ftpStream); }
Progress monitoring
If you need to track the progress of the download, you must copy the contents in parts:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Ftp.UploadFile; using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip")) using (Stream ftpStream = request.GetRequestStream()) { byte[] buffer = new byte[10240]; int read; while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0) { ftpStream.Write(buffer, 0, read); Console.WriteLine("Uploaded {0} bytes", fileStream.Position); } }
For more information about the graphical interface (WinForms ProgressBar ), see the C # example at:
How can we show the progress bar for loading with FtpWebRequest
Download Folder
If you want to download all files from a folder, see
Download the file directory using WebClient .
Martin Prikryl Aug 16 '17 at 5:42 on 2017-08-16 05:42
source share