2011-12-26 57 views
3

现在我知道如何将文件从一个目录复制到另一个目录,这非常简单。如何从FTP(使用C#)获取文件?

但现在我需要对来自FTP服务器的文件进行相同的操作。你可以给我一些例子,如何从FTP更改文件名时获取文件?

回答

6

看看How to: Download Files with FTPdownloading all files in directory ftp and c#

// Get the object used to communicate with the server. 
      FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm"); 
      request.Method = WebRequestMethods.Ftp.DownloadFile; 

      // This example assumes the FTP site uses anonymous logon. 
      request.Credentials = new NetworkCredential ("anonymous","[email protected]"); 

      FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 

      Stream responseStream = response.GetResponseStream(); 
      StreamReader reader = new StreamReader(responseStream); 
      Console.WriteLine(reader.ReadToEnd()); 

      Console.WriteLine("Download Complete, status {0}", response.StatusDescription); 

      reader.Close(); 
      reader.Dispose(); 
      response.Close(); 

编辑 如果要重命名FTP服务器上的文件来看看这Stackoverflow question

+2

我会把你的阅读器放在一个使用块中以便妥善处理。否则,在最后添加reader.Dispose()。 – Xcalibur37 2011-12-26 15:23:15

+0

我知道这是MS内容的复制/粘贴,但它仍然没有干净的书写。 – Xcalibur37 2011-12-26 15:25:32

+0

我知道我需要保存我的本地字典中的文件,然后才能重命名它?但我可以直接做吗? – revolutionkpi 2011-12-26 15:27:23

1

最微不足道的方式来下载的二进制文件从使用.NET框架的FTP服务器使用WebClient.DownloadFile

它采用源远程文件和目标本地文件的路径。所以如果你需要的话,你可以使用不同的名字作为本地文件。

WebClient client = new WebClient(); 
client.Credentials = new NetworkCredential("username", "password"); 
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip"); 

如果你需要更大的控制,即WebClient不提供(如TLS/SSL加密等),使用FtpWebRequest。简单的方法是只是一个FTP响应流中使用Stream.CopyTo复制到FileStream:如果您需要监视下载进度

FtpWebRequest request = 
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); 
request.Credentials = new NetworkCredential("username", "password"); 
request.Method = WebRequestMethods.Ftp.DownloadFile; 

using (Stream ftpStream = request.GetResponse().GetResponseStream()) 
using (Stream fileStream = File.Create(@"C:\local\path\file.zip")) 
{ 
    ftpStream.CopyTo(fileStream); 
} 

,你必须块自己的内容复制:

FtpWebRequest request = 
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); 
request.Credentials = new NetworkCredential("username", "password"); 
request.Method = WebRequestMethods.Ftp.DownloadFile; 

using (Stream ftpStream = request.GetResponse().GetResponseStream()) 
using (Stream fileStream = File.Create(@"C:\local\path\file.zip")) 
{ 
    byte[] buffer = new byte[10240]; 
    int read; 
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     fileStream.Write(buffer, 0, read); 
     Console.WriteLine("Downloaded {0} bytes", fileStream.Position); 
    } 
} 

对于GUI进度(的WinForms ProgressBar),请参阅:
FtpWebRequest FTP download with ProgressBar

如果你想从一个远程文件夹下载的所有文件,请参阅
C# Download all files and subdirectories through FTP

相关问题