2011-12-26 2 views

답변

6

것은 How to: Download Files with FTP 봐 또는 downloading 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(); 

편집 당신은 바이너리 파일을 다운로드하는 가장 사소한 방법이 Stackoverflow question

+2

적절한 처분을 위해 독자를 사용하는 블록으로 묶을 것입니다. 그렇지 않으면 끝에 reader.Dispose()를 추가하십시오. – Xcalibur37

+0

나는 이것이 MS 콘텐츠의 복사/붙여 넣기라는 것을 알고 있지만, 여전히 깨끗하게 쓰여지지는 않았다. – Xcalibur37

+0

필자는 로컬 dict에 파일을 저장해야하며 그 다음에 이름을 변경해야한다는 것을 알고 있습니다. 하지만 직접 할 수 있을까요? – revolutionkpi

1

을 살펴 FTP 서버에 파일의 이름을 변경하려면 . NET Framework를 사용하는 FTP 서버에서 WebClient.DownloadFile을 사용하고 있습니다.

원본 원격 파일과 대상 로컬 파일의 경로가 필요합니다. 필요한 경우 로컬 파일에 다른 이름을 사용할 수 있습니다. (TLS/SSL 암호화 등이 같은), FtpWebRequest를 사용

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은 제공하지 않습니다. 쉬운 방법은 바로 Stream.CopyTo을 사용 FileStream에 FTP 응답 스트림을 복사하는 것입니다 : GUI를 들어

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); 
    } 
} 

:

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); 
} 

을 당신이 다운로드 진행 상황을 모니터링해야하는 경우, 당신은 덩어리 직접 내용을 복사해야 진행 (윈폼 ProgressBar)을 참조하십시오
FtpWebRequest FTP download with ProgressBar

원격 폴더에서 모든 파일을 다운로드 할 경우,
01 참조C# Download all files and subdirectories through FTP.

관련 문제