using System; using System.IO; //webClient using System.Net; using WinSCP; namespace SmartFTP.Logic { class FTPTransferUtil { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); public static int UploadFile(string sourceFolder, string sourceFileName, string ftpServer, string ftpPath, string userName, string password) { int res = -1; try { int port = -1; var parts = ftpServer.Split(':'); if (parts.Length > 1) { int.TryParse(parts[parts.Length - 1], out port); if (port != -1) { ftpServer = ftpServer.Replace(":" + port.ToString(), "");// removing port part from server } } logger.Debug(String.Concat(sourceFolder, sourceFileName)); SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = ftpServer, UserName = userName, Password = password, }; if (port != -1) { sessionOptions.PortNumber = port; } using (Session session = new Session()) { // Connect session.Open(sessionOptions); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(sourceFolder+sourceFileName, ftpPath, false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { logger.Debug("Upload of {0} succeeded", transfer.FileName); } } return 1; } catch (System.Net.WebException wexc) { logger.Debug("-2"); logger.Error(wexc.InnerException); logger.Error(wexc.Message); Console.WriteLine(wexc.Message); return -2; } catch (Exception ex) { logger.Debug("-1"); logger.Error(ex.InnerException); logger.Error(ex.Message); Console.WriteLine(ex.Message); res = -1; } return res; } } }