how to download compressed file (.zip) thr

2019-06-28 07:12发布

How to download .zip file format using c# code?

Here is the code, i am using to download. Just to highlight, If i download .txt file, it works fine. If i download .zip file, it downloads the .zip file but i can't open this. It complains that .zip is in incorrect format. I have doubt in how i am writing back the file on local drive.

Help?

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; 

5条回答
forever°为你锁心
2楼-- · 2019-06-28 07:30
using System.Net;
// ...

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

Answer to the updated question:

The way you are saving the stream to disk is wrong. You are treating the stream as a character sequence, which corrupts the ZIP file in the process. Open a FileStream instead of a StreamWriter and copy the GetResponseStream() return value directly to that FileStream using something like my CopyStream function from here.

查看更多
霸刀☆藐视天下
3楼-- · 2019-06-28 07:32

A good alternative for unzipping is http://www.codeplex.com/DotNetZip.

If you need to download SSH or SSL encryption then I recommend this component: http://www.weonlydo.com/index.asp?showform=FtpDLX.NET. Also great for plain FTP.

查看更多
欢心
4楼-- · 2019-06-28 07:35

For all of you who found these answers unhelpful, I found a better answer here:

Downloading ZIP file from FTP and copying to folder within website

查看更多
Emotional °昔
5楼-- · 2019-06-28 07:41

The .NET Framework's System.Net namespace offers the FTPWebRequest class. Here's an article explaining how to use it:

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

查看更多
姐就是有狂的资本
6楼-- · 2019-06-28 07:46

You would probably want to make use of the FtpWebRequest class to download the .zip file, then the System.IO.Packaging class to extract its contents.

查看更多
登录 后发表回答