将文件从ftp下载到本地驱动器

时间:2013-11-19 16:22:23

标签: ftp

在FTP子文件夹中包含一些想要下载到一个csv文件中的本地驱动器文件夹的csv文件。 在FTP中,每个csv文件只包含一个记录。所以,现在我想在一个csv文件中将所有5条记录放入localdrive文件夹中。这里的代码仅适用于一个csv文件。

   private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
   {
       //FileStream responseStream =null;
        int Length = 2048;
        Byte[] buffer = new Byte[Length];


     //   int bytesRead = responseStream.Read(buffer, 0, Length);
        int bytesRead = 0;
        FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, false);

        request.Method = WebRequestMethods.Ftp.DownloadFile;

        Stream reader = request.GetResponse().GetResponseStream();
        FileStream fileStream = new FileStream(localDestinationFilePath, FileMode.Create);

        while (true )
        {
            bytesRead = reader.Read(buffer,0,buffer.Length);
            if (bytesRead == 0)
                break;


            fileStream.Write(buffer, 0, bytesRead);
        }

        fileStream.Close();
    }
    private FtpWebRequest CreateFtpWebRequest(string ftpDirectoryPath, string userName, string password, bool keepAlive)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirectoryPath));

        //Set proxy to null. Under current configuration if this option is not set then the proxy that is used will get an html response from the web content gateway (firewall monitoring system)
        request.Proxy = null;

        request.UsePassive = true;
        request.UseBinary = true;
        request.KeepAlive = keepAlive;

        request.Credentials = new NetworkCredential(userName, password);

        return request;
    }


    private void button1_Click(object sender, EventArgs e)
    {
        DownloadFile("Username1", "Password1", "ftp://172.32.1.252:5010/Test/CBRE/building.csv", "C://Workspace/ex.csv");

    }

1 个答案:

答案 0 :(得分:0)

我不确切地知道你要做什么,但你也可以尝试这种方式:

WebClient Client = new WebClient ();
Client.DownloadFile(http://www.domain.com/files/yourfile.ext, " yourfile.ext");

WebClientClass