Home >Backend Development >C++ >How to Upload and Download Files to/from FTP Servers using C#/.NET?
Uploading Files
To upload a file to an FTP server, you can use WebClient.UploadFile or FtpWebRequest. To use WebClient, simply provide the FTP URL and the local file path:
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");
For more control, use FtpWebRequest:
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); }
Downloading Files
To download a file from an FTP server, use WebClient.DownloadFile or FtpWebRequest. To use WebClient, provide the FTP URL and the local file path:
WebClient client = new WebClient(); client.Credentials = new NetworkCredential("username", "password"); client.DownloadFile("ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
For more control, use FtpWebRequest:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Ftp.DownloadFile; using (Stream ftpStream = request.GetResponse().GetResponseStream()) using (Stream fileStream = File.Create(@"C:\local\path\file.zip")) { ftpStream.CopyTo(fileStream); }
The above is the detailed content of How to Upload and Download Files to/from FTP Servers using C#/.NET?. For more information, please follow other related articles on the PHP Chinese website!