using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; namespace vCloud.GeneratePackages.Tool { class FtpHelper { private const int bufferSize = 8192; /* FTP Get */ public static void Get(string remoteFile, string localFile, Action procressCallback = null, string user = "anonymous", string pass = null) { try { /* Create an FTP Request */ var ftpRequest = (FtpWebRequest)FtpWebRequest.Create(remoteFile); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; /* Establish Return Communication with the FTP Server */ var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Get the FTP Server's Response Stream */ var ftpStream = ftpResponse.GetResponseStream(); /* Open a File Stream to Write the Downloaded File */ FileStream localFileStream = new FileStream(localFile, FileMode.Create); /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[bufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); /* Download the File by Writing the Buffered Data Until the Transfer is Complete */ try { while (bytesRead > 0) { localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); procressCallback?.Invoke(localFileStream.Length); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ localFileStream.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return; } /// /// get file list /// /// /// public static IList GetFileList(string url, string user = "anonymous", string pass = null) { FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(url); ftpRequest.Credentials = new NetworkCredential(user, pass); ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse(); StreamReader streamReader = new StreamReader(response.GetResponseStream()); List directories = new List(); string line = streamReader.ReadLine(); while (!string.IsNullOrEmpty(line)) { directories.Add(line); line = streamReader.ReadLine(); } streamReader.Close(); return directories; } } }