Download ZIP file from FTP and copy to folder on website

Finding some problems when copying a zip file from an FTP address. It is just copying and an empty file, so I believe that something is wrong using StreamReader or StreamWriter.

Here is the code:

//read through directory details response string line = reader.ReadLine(); while (line != null) { if (line.EndsWith("zip")) //"d" = dir don't need "." or ".." dirs { FtpWebRequest downloadRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftpHost + line); //new Uri("ftp://" + ftpServerIP + DestinationFolder + fileInf.Name)); downloadRequest.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["FilesUser"], ConfigurationManager.AppSettings["FilesPass"]); downloadRequest.KeepAlive = false; downloadRequest.UseBinary = true; downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile; string folderToWrite = HttpContext.Current.Server.MapPath("~/Routing/RoutingFiles/"); string folderToSave = HttpContext.Current.Server.MapPath("~/Routing/"); StreamReader downloadRequestReader = new StreamReader(downloadRequest.GetResponse().GetResponseStream()); DirectoryInfo downloadDirectory = new DirectoryInfo(folderToWrite); FileInfo file = new FileInfo(Path.Combine(downloadDirectory.FullName, line)); if (!file.Exists) { StreamWriter writer = new StreamWriter(Path.Combine(folderToWrite, line), false); writer.Write(downloadRequestReader.ReadToEnd()); using (var downloadResponseStream = response.GetResponseStream()) { } } } } 

By the time it reaches the end of this section, the file has been copied but empty, so I don't think I'm reading the stream for the zip file correctly. Any ideas? I saw talk that FileStream is better at loading Zip files, but I couldn't get this to work.

Thanks.

+3
source share
1 answer

Here is an example that downloads a file from ftp.

 try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpAddr + "test.zip"); request.Credentials = new NetworkCredential(userName, password); request.UseBinary = true; // Use binary to ensure correct dlv! request.Method = WebRequestMethods.Ftp.DownloadFile; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); FileStream writer = new FileStream("test.zip", FileMode.Create); long length = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[2048]; readCount = responseStream.Read(buffer, 0, bufferSize); while (readCount > 0) { writer.Write(buffer, 0, readCount); readCount = responseStream.Read(buffer, 0, bufferSize); } responseStream.Close(); response.Close(); writer.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } 

Change Sorry for the error in the previous code.

When fixing my previous code, I found a useful resource: example

+11
source

Source: https://habr.com/ru/post/1301158/


All Articles