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

时间:2011-06-23 08:31:05

标签: c# .net ftp network-programming

查找从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文件的说法,但我无法让它工作。

感谢。

1 个答案:

答案 0 :(得分:11)

以下是从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());
}

修改我很抱歉以前的代码中出现错误。

在更正我之前的代码时,我发现以下资源非常有用:example