【问题标题】:how to download compressed file (.zip) through FTP using c#?如何使用 c# 通过 FTP 下载压缩文件(.zip)?
【发布时间】:2010-02-12 21:24:05
【问题描述】:

如何使用c#代码下载.zip文件格式?

这是我用来下载的代码。只是为了强调,如果我下载 .txt 文件,它工作正常。如果我下载 .zip 文件,它会下载 .zip 文件,但我无法打开它。它抱怨 .zip 格式不正确。我怀疑我如何在本地驱动器上写回文件。

帮助?

string ftpServerIP = FTPServer;
string ftpUserID = FTPUser;
string ftpPassword = FTPPwd;
FileInfo fileInf = new FileInfo(FileName);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri); //new Uri("ftp://" + ftpServerIP + DestinationFolder + fileInf.Name));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.EnableSsl = true;
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
//reqFTP.UsePassive = true;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
//Stream strm = reqFTP.GetRequestStream();
StreamReader reader = new StreamReader(reqFTP.GetResponse().GetResponseStream());
StreamWriter writer = new StreamWriter(Path.Combine(FolderToWriteFiles, FileName), false);
writer.Write(reader.ReadToEnd());
return true; 

【问题讨论】:

标签: c# ftp sftp ftpwebrequest


【解决方案1】:
using System.Net;
// ...

new WebClient().DownloadFile("ftp://ftp.someurl.com/file.zip",
                             "C:\\downloadedFile.zip");

更新问题的答案:

您将流保存到磁盘的方式是错误的。您将流视为字符序列,这会破坏过程中的 ZIP 文件。打开FileStream 而不是StreamWriter,然后使用my CopyStream function from here 之类的东西将GetResponseStream() 返回值直接复制到FileStream

【讨论】:

  • 我可以使用 FtpWebRequest 类做点什么吗?
  • 这假设 FTP 服务器不需要登录。 FtpWebRequest 类更适合需要登录的 ftp 服务器。
  • @user144842:是的,但是WebClient 将其抽象掉了。如果您只需要下载文件而无需更多控制,请使用WebClient
  • @rally25rs。我的服务器需要登录验证。
  • @user144842:那么WebClient 将不适合您。需要直接使用WebRequest.CreateFtpWebRequestWebClient内部实际上使用WebRequest,这是一个抽象类,为不同的协议创建XXXWebRequest类。)
【解决方案2】:

.NET Framework 的 System.Net 命名空间提供 FTPWebRequest 类。这是一篇解释如何使用它的文章:

http://www.vcskicks.com/download-file-ftp.php

【讨论】:

    【解决方案3】:

    您可能希望使用 FtpWebRequest class 下载 .zip 文件,然后使用 System.IO.Packaging 类来提取其内容。

    【讨论】:

      【解决方案4】:

      解压缩的一个不错的选择是http://www.codeplex.com/DotNetZip

      如果您需要下载 SSH 或 SSL 加密,那么我推荐这个组件:http://www.weonlydo.com/index.asp?showform=FtpDLX.NET。也非常适合普通 FTP。

      【讨论】:

      • 这是我使用的,对于 FTP 上的 zip 文件,请确保使用 FileStream!
      【解决方案5】:

      对于所有认为这些答案没有帮助的人,我在这里找到了更好的答案:

      Downloading ZIP file from FTP and copying to folder within website

      【讨论】:

        猜你喜欢
        • 2017-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        • 2018-06-19
        • 1970-01-01
        相关资源
        最近更新 更多