Home > Backend Development > C++ > How to Efficiently Upload and Download Files to/from an FTP Server in C#?

How to Efficiently Upload and Download Files to/from an FTP Server in C#?

Mary-Kate Olsen
Release: 2025-01-11 09:22:40
Original
445 people have browsed it

How to Efficiently Upload and Download Files to/from an FTP Server in C#?

Uploading and downloading FTP server files in C#/.NET

Question 1: Streaming file upload

To avoid loading large files into memory before uploading, use FileStream and Stream.CopyTo to transfer files directly. The modified code is as follows:

<code class="language-csharp">using (Stream ftpStream = request.GetRequestStream())
using (Stream fileStream = File.OpenRead(@"/local/path/to/file.zip"))
{
    fileStream.CopyTo(ftpStream);
}</code>
Copy after login

Problem 2: The ZIP file is invalid after downloading

Confirm whether the FTP server supports pasv mode (passive mode data transfer) by enabling request.UsePassive = true. Additionally, set request.UseBinary = true to transfer files in binary mode. The modified code is as follows:

<code class="language-csharp">FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.UsePassive = true;
request.UseBinary = true;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"/local/path/to/file.zip"))
{
    ftpStream.CopyTo(fileStream);
}</code>
Copy after login

With the above modifications, you can successfully upload and download files to the FTP server, ensuring the integrity of the ZIP file after downloading.

The above is the detailed content of How to Efficiently Upload and Download Files to/from an FTP Server in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template