如何从FTP服务器下载Zip文件

时间:2011-12-13 18:57:49

标签: c# ftp

我在ftp服务器上有zip文件,这个zip文件包含多个xml文件,我想下载这个zipfile并保存到本地磁盘,我已经写下面的代码,我下载文件但是当我尝试提取时这个拉链让我误以为文件已损坏......

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();

3 个答案:

答案 0 :(得分:3)

您正在通过StreamReader引导FTP请求的结果。这通常具有处理字符编码的有益效果,但在处理二进制数据(即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();

答案 1 :(得分:1)

以下是FTP服务器下载文件的示例代码

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();
}

答案 2 :(得分:0)

我认为您的问题是您下载zip的方式,这是一篇解释如何使用它的文章,我希望它有所帮助:

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

此外,这里有一个问题:

how to download compressed file (.zip) through FTP using c#?