Home >Backend Development >C++ >How to Upload and Download Files to/from FTP Servers using C#/.NET?

How to Upload and Download Files to/from FTP Servers using C#/.NET?

Susan Sarandon
Susan SarandonOriginal
2025-01-11 11:14:44616browse

How to Upload and Download Files to/from FTP Servers using C#/.NET?

Uploading and Downloading Files to and from FTP Servers in 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn