从FTP下载ZIP文件并复制到网站内的文件夹

本文关键字:网站 文件夹 复制 FTP 下载 ZIP 文件 | 更新日期: 2023-09-27 18:00:23

从FTP位置复制zip文件时发现一些问题。它只是复制和空文件,所以我认为我使用StreamReader或StreamWriter有问题。

这是代码:

//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())
            {
            }
        }
    }
}

当它到达该部分的底部时,文件已经被复制,但是空的,所以我认为我没有正确读取zip文件的流。有什么想法吗?我看到有人说FileStream更适合下载Zip文件,但我也无法做到这一点。

谢谢。

从FTP下载ZIP文件并复制到网站内的文件夹

下面是一个从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());
}

编辑我对以前代码中的错误感到抱歉。

在更正以前的代码时,我发现以下资源很有用:示例