/// <summary> /// Create a new FtpWebRequest with the specified connection details, /// path, and method, while handling exceptions that may occur by /// wrapping them in an FtpRequestException with additional info before /// re-throwing them. /// <br /> /// For valid <paramref name="method"/> strings, use methods in <see cref="WebRequestMethods.Ftp"/> /// </summary> /// <param name="conn">FtpConnectionInfo object, representing connection details</param> /// <param name="path">The path of the request (ex: /path/to/request)</param> /// <param name="method">The request method </param> /// <param name="timeout">(optional) timeout in milliseconds - default: 5000</param> /// <returns><see cref="FtpWebRequest"/> - request object for specified options.</returns> /// <exception cref="FtpRequestException">There was a problem with creating or configuring the request.</exception> private static FtpWebRequest Request(FtpConnectionInfo conn, string path, string method, int timeout = 5000) { var uri = "ftp://" + conn.FullUri + path; var user = conn.Username; var pass = conn.Password; FtpWebRequest request = null; try { request = WebRequest.Create(uri) as FtpWebRequest; request.Method = method; request.Credentials = new NetworkCredential(user, pass); request.KeepAlive = false; request.Timeout = timeout; //not needed, as they already default to true //request.UseBinary = true; //request.UsePassive = true; } catch (SecurityException e) { throw new FtpRequestException("Request security exception: " + e.Message, request, e); } catch (FormatException e) { throw new FtpRequestException("Request format exception: " + e.Message, request, e); } catch (Exception e) { throw new FtpRequestException("Request failed: " + e.Message, request, e); } return(request); }
private void WriteFtpFile(FtpConnectionInfo connectionInfo, string outputPath, Stream stream) { UriBuilder uriBuilder = new UriBuilder("ftp", connectionInfo.Server, connectionInfo.PortNumber, outputPath); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uriBuilder.Uri); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(connectionInfo.Login, connectionInfo.Password); byte[] fileContents; stream.Position = 0; using (MemoryStream ms = new MemoryStream()) { stream.CopyTo(ms); fileContents = ms.ToArray(); } request.ContentLength = fileContents.Length; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(fileContents, 0, fileContents.Length); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) if (response.StatusCode != FtpStatusCode.CommandOK) { throw new FtpUploadException(response.StatusCode, response.StatusDescription); } }
/// <summary> /// Downloads the contents of the specified file path from the /// specified FTP server. /// </summary> /// <param name="conn">server connection info</param> /// <param name="path">file path to download</param> /// <returns>A string containing the files raw contents</returns> /// <exception cref="FtpRequestException"></exception> /// <exception cref="FtpResponseException"></exception> public static string DownloadFile(FtpConnectionInfo conn, string path) { var request = Request(conn, path, DOWNLOAD); var response = TryResponse(request); if (response.StatusCode == FtpStatusCode.OpeningData) { try { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { return(reader.ReadToEnd()); } } } catch (Exception e) { throw new FtpResponseException("error reading response stream while downloading file: " + path, e); } } throw new FtpResponseException("Unable to download file (incorrect status code): " + path); }
/// <summary> /// Performs a test of the FTP connection details provided, returning the /// server welcome message if succesful, otherwise throwing an exception. /// </summary> /// <param name="conn">connection info to test</param> /// <returns>Server welcome message</returns> /// <exception cref="FtpRequestException">Problem with request.</exception> /// <exception cref="FtpResponseException">Problem with response</exception> public static string Test(FtpConnectionInfo conn) { var request = Request(conn, "/", LIST); var response = TryResponse(request); if (response.StatusCode == FtpStatusCode.OpeningData) { return(response.WelcomeMessage); } throw new FtpResponseException("Unexpected response: ", response); }
private IEnumerable <FtpFilesValue> GetFiles(FtpConnectionInfo connectionInfo, string path) { UriBuilder uriBuilder = new UriBuilder("ftp", connectionInfo.Server, connectionInfo.PortNumber, path); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uriBuilder.Uri); request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = new NetworkCredential(connectionInfo.Login, connectionInfo.Password); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) using (StreamReader reader = new StreamReader(response.GetResponseStream())) while (!reader.EndOfStream) { yield return(new FtpFilesValue(connectionInfo, path, reader.ReadLine())); } }
/// <summary> /// Get's a list of <see cref="FtpFileInfo"/> objects representing all the /// files in the provided path (<paramref name="worldPath"/>) /// </summary> /// <param name="conn">connection details</param> /// <param name="worldPath">path to list contents of (normalized automatically)</param> /// <returns> /// List of <see cref="FtpFileInfo"/> objects representing every file /// and directory inside the <paramref name="worldPath"/> directory. /// </returns> /// <exception cref="FtpException"> /// If there was an error with the <paramref name="worldPath"/> /// parameter, or the 150 Opening data status code is not returned /// upon intial response from te server.</exception> /// <exception cref="FtpRequestException">If there was a problem with the request.</exception> /// <exception cref="FtpResponseException">If there was a problem with the response.</exception> public static List <FtpFileInfo> ListFiles(FtpConnectionInfo conn, string worldPath) { try { //clever trick to remove leading/trailing slashes on the world path. slashes will be added automatically worldPath = String.Join("/", worldPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)); } catch (ArgumentException e) { throw new FtpException("Invalid world path: " + worldPath, e); } var request = Request(conn, "/" + worldPath, LIST); var response = TryResponse(request); if (response.StatusCode == FtpStatusCode.OpeningData) { var files = new List <FtpFileInfo>(); using (Stream responseStream = response.GetResponseStream()) //usings to ensure stream cleanup { using (StreamReader reader = new StreamReader(responseStream)) { while (!reader.EndOfStream) { var line = reader.ReadLine(); try { var ftpInfo = new FtpFileInfo(line); files.Add(ftpInfo); } catch (FtpFileStringFormatException e) { Console.WriteLine("[Ftp.ListFiles] - error parsing file info"); Console.WriteLine("[Ftp.ListFiles] - " + e); } Console.WriteLine(line); } return(files); } } } //throw exception if we don't get the 150 Opening data status code throw new FtpException("not connected"); }
public void PushValues(FtpFilesValuesProviderArgs args, FtpConnectionInfo connectionInfo, Action <FtpFilesValue> pushValue) { GetFiles(connectionInfo, args.Path).ToList().ForEach(pushValue); }
public FtpFilesValue(FtpConnectionInfo connectionInfo, string path, string name) { this.Name = name; this._path = path; this._connectionInfo = connectionInfo; }