using System; using System.IO; using System.Net; using System.Text; public class FtpClientWrapper { public string Server { get; private set; } public string Username { get; private set; } private string Password { get; set; } public FtpClientWrapper(string server, string username, string password) { Server = server; if (!Server.EndsWith("/")) Server += "/"; Username = username; Password = password; } public bool UploadFile(string localFile, string remotePath, string remoteFile) { // Adapted from https://msdn.microsoft.com/en-us/library/ms229715%28v=vs.110%29.aspx try { var serverTarget = UrlPath.Combine(Server, remotePath, remoteFile); var request = (FtpWebRequest)WebRequest.Create("ftp://" + serverTarget); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(Username, Password); byte[] contents; using (var sr = new StreamReader(localFile)) { contents = Encoding.UTF8.GetBytes(sr.ReadToEnd()); sr.Close(); } request.ContentLength = contents.Length; using (var requestStream = request.GetRequestStream()) { requestStream.Write(contents, 0, contents.Length); requestStream.Close(); } using (var response = (FtpWebResponse)request.GetResponse()) { var status = response.StatusDescription; response.Close(); return true; } } catch (Exception ex) { // return false; throw; } } public void DownloadFile(string remotePath, string remoteFile, string localFile) { var serverSource = UrlPath.Combine(Server, remotePath, remoteFile); // Get the object used to communicate with the server. var request = (FtpWebRequest)WebRequest.Create("ftp://" + serverSource); request.Method = WebRequestMethods.Ftp.DownloadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential(Username, Password); var response = (FtpWebResponse)request.GetResponse(); using (var responseStream = response.GetResponseStream()) { using (var reader = new StreamReader(responseStream)) { var s = reader.ReadToEnd(); File.WriteAllText(localFile, s); reader.Close(); response.Close(); } } } }