如何从FTP服务器下载ZipFile

本文关键字:下载 ZipFile 服务器 FTP | 更新日期: 2023-09-27 18:17:39

我在ftp服务器上有zip文件,这个zip文件中包含多个xml文件,我想下载这个zip文件并保存到本地磁盘,我已经写了下面的代码,我下载文件,但当我试图提取这个zip时,它给我的错误是文件损坏......

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + file);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
StreamWriter writer = new StreamWriter(destination);
writer.Write(reader.ReadToEnd());
writer.Close();
reader.Close();
response.Close();

如何从FTP服务器下载ZipFile

您正在将FTP请求的结果通过StreamReader进行通道传输。这在处理字符编码时通常具有有益的效果,但在处理二进制数据(即zip文件)时不会想要这样做。相反,您应该直接从流中读取数据。比如:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + file);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// Copy the data from the responseStream to destination 1k at a time (feel free to increase buffer size)
byte[] buffer = new byte[1024];
for (int amountRead = responseStream.Read(buffer, 0, buffer.Length); amountRead > 0; amountRead = responseStream.Read(buffer, 0, buffer.Length))
{
    destination.Write(buffer, 0, amountRead);
}
destination.Flush();
response.Close();

从FTP Server下载文件

Uri url = new Uri("ftp://ftp.demo.com/file1.txt");
if (url.Scheme == Uri.UriSchemeFtp)
{
    FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url);
    //Set credentials if required else comment this Credential code
    NetworkCredential objCredential = new NetworkCredential("FTPUserName", "FTPPassword");
    objRequest.Credentials = objCredential;
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
    FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
    StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
    byte[] buffer = new byte[16 * 1024];
    int len = 0;
    FileStream objFS = new FileStream(Server.MapPath("file1.txt"), FileMode.Create, FileAccess.Write, FileShare.Read);
    while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        objFS.Write(buffer, 0, len);
    }
    objFS.Close();
    objResponse.Close();
}

我认为你的问题是你下载压缩包的方式,这里有一篇文章解释如何使用它,希望对你有所帮助:

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

同样,这里有一个这样的问题:

如何使用c#通过FTP下载压缩文件(.zip) ?