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>
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>
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!