2025-06-03 15:11:16 +02:00

84 lines
2.6 KiB
C#

using System;
using System.IO; //webClient
using System.Net;
using WinSCP;
using NLog;
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.Debugs(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.Debugs(string.Format("Upload of {0} succeeded", transfer.FileName));
}
}
return 1;
}
catch (System.Net.WebException wexc)
{
logger.Debugs("-2");
logger.Errors(wexc);
return -2;
}
catch (Exception ex)
{
logger.Debugs("-1");
logger.Errors(ex);
res = -1;
}
return res;
}
}
}