Last active
December 16, 2015 20:28
-
-
Save benerdin/5492170 to your computer and use it in GitHub Desktop.
.NET FTP Code- List files- Delete files- Upload a file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using NLog; | |
| using System; | |
| using System.Collections.Generic; | |
| using System.IO; | |
| using System.Linq; | |
| using System.Net; | |
| using System.Text; | |
| namespace Brian.Federici | |
| { | |
| /// <summary> | |
| /// The object responsible for uploading index files via FTP. | |
| /// </summary> | |
| class FtpSolrDataPublisher : IFtpDataPublisher | |
| { | |
| /// <summary> | |
| /// Attempts to publish <paramref name="fileInfo"/> to an FTP server. | |
| /// </summary> | |
| bool IFtpDataPublisher.Publish(FileInfo fileInfo) | |
| { | |
| try | |
| { | |
| // Create FTP request with the proper credentials. | |
| var request = GetRequest(fileInfo.Name); | |
| request.ContentLength = fileInfo.Length; | |
| request.Method = WebRequestMethods.Ftp.UploadFile; | |
| // Read file into byte array and write the file to the request stream. | |
| var fileContents = GetFileContents(fileInfo); | |
| using (var requestStream = request.GetRequestStream()) | |
| { | |
| requestStream.Write(fileContents, 0, fileContents.Length); | |
| } | |
| // Get response | |
| using (var response = (FtpWebResponse)request.GetResponse()) | |
| { | |
| // Return success/failure | |
| return response.StatusCode == FtpStatusCode.CommandOK | |
| || response.StatusCode == FtpStatusCode.ClosingData; | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.FatalException(ex.ToString(), ex); | |
| return false; | |
| } | |
| } | |
| /// <summary> | |
| /// Attempts to delete all files from the FTP server. | |
| /// </summary> | |
| bool IFtpDataPublisher.CleanupDestination() | |
| { | |
| try | |
| { | |
| // Get all uploaded files. | |
| var files = GetUploadedFiles(); | |
| // Delete each file from the FTP server. | |
| files.ForEach( | |
| filename => | |
| { | |
| // Create FTP request with the proper credentials. | |
| var request = GetRequest(filename); | |
| request.Method = WebRequestMethods.Ftp.DeleteFile; | |
| // Get response | |
| using ((FtpWebResponse)request.GetResponse()) { } | |
| }); | |
| return true; | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.FatalException(ex.ToString(), ex); | |
| return false; | |
| } | |
| } | |
| private IEnumerable<string> GetUploadedFiles() | |
| { | |
| try | |
| { | |
| // Create request. | |
| var request = GetRequest(); | |
| request.Method = WebRequestMethods.Ftp.ListDirectory; | |
| // Get response and read in the data. | |
| using (var response = (FtpWebResponse)request.GetResponse()) | |
| using (var stream = response.GetResponseStream()) | |
| using (var reader = new StreamReader(stream)) | |
| { | |
| // Parse out filenames. | |
| var data = reader.ReadToEnd(); | |
| if (!string.IsNullOrWhiteSpace(data)) | |
| { | |
| return data.Split( | |
| new[] { Environment.NewLine }, | |
| StringSplitOptions.RemoveEmptyEntries | |
| ).ToList(); | |
| } | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.ErrorException(ex.ToString(), ex); | |
| } | |
| return new List<string>(0); | |
| } | |
| private FtpWebRequest GetRequest(string filename = null) | |
| { | |
| // Create FTP request with the proper credentials. | |
| var uriString = string.Format( | |
| "ftp://<IP>/<folder>/{0}", | |
| filename | |
| ); | |
| var request = (FtpWebRequest)FtpWebRequest.Create(uriString); | |
| request.Credentials = new NetworkCredential("username", "password"); | |
| // Note: KeepAlive must be set to "false" to prevent too many connections | |
| // from being open to the FTP server. When it was set to "true," the | |
| // following exception would always get thrown during the upload process: | |
| // "The underlying connection was closed: An unexpected error occurred on a receive." | |
| request.KeepAlive = false; | |
| return request; | |
| } | |
| /// <summary> | |
| /// Returns file contents as byte array. | |
| /// </summary> | |
| private static byte[] GetFileContents(FileInfo fileInfo) | |
| { | |
| using (var sourceStream = new StreamReader(fileInfo.FullName)) | |
| { | |
| return Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); | |
| } | |
| } | |
| /// <summary> | |
| /// The logger. | |
| /// </summary> | |
| private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Collections.Generic; | |
| using System.IO; | |
| namespace Brian.Federici | |
| { | |
| interface IFtpDataPublisher | |
| { | |
| /// <summary> | |
| /// Attempts to publish <paramref name="fileInfo"/> to an FTP server. | |
| /// </summary> | |
| bool Publish(FileInfo fileInfo); | |
| /// <summary> | |
| /// Attempts to cleanup all files from the FTP server. | |
| /// </summary> | |
| bool CleanupDestination(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment