97 lines
3.3 KiB
C#
97 lines
3.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Configuration;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using WinSCP;
|
|
|
|
namespace SmartFTPThread.Logic
|
|
{
|
|
class FTPTransferUtil
|
|
{
|
|
|
|
private static string logPath = ConfigurationManager.AppSettings["LogPath"];
|
|
|
|
public static int UploadFile(string sourceFolder, string sourceFileName)
|
|
{
|
|
|
|
|
|
var logString = string.Format("File: {0}\\{1}", sourceFolder, sourceFileName);
|
|
log(logString);
|
|
|
|
int res = -1;
|
|
try
|
|
{
|
|
string ftpPath = ConfigurationManager.AppSettings["FTPFolder"];
|
|
SessionOptions sessionOptions = new SessionOptions
|
|
{
|
|
Protocol = Protocol.Ftp,
|
|
HostName = ConfigurationManager.AppSettings["FTPServer"],
|
|
UserName = ConfigurationManager.AppSettings["FTPUser"],
|
|
Password = ConfigurationManager.AppSettings["FTPPassword"]
|
|
};
|
|
|
|
logString = string.Format("ftpPath: {0} HostName: {1} UserName: {2} Password: {3}", ftpPath, ConfigurationManager.AppSettings["FTPServer"], ConfigurationManager.AppSettings["FTPUser"], ConfigurationManager.AppSettings["FTPPassword"]);
|
|
log(logString);
|
|
|
|
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)
|
|
{
|
|
Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
|
|
log(string.Format("Upload of {0} succeeded", transfer.FileName));
|
|
}
|
|
}
|
|
return 1;
|
|
}
|
|
catch (System.Net.WebException wexc)
|
|
{
|
|
Console.WriteLine("-2");
|
|
Console.WriteLine(wexc.InnerException);
|
|
Console.WriteLine(wexc.Message);
|
|
log(wexc.InnerException.ToString());
|
|
log(wexc.Message);
|
|
return -2;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine("-1");
|
|
Console.WriteLine(ex.InnerException);
|
|
Console.WriteLine(ex.Message);
|
|
log(ex.InnerException.ToString());
|
|
log(ex.Message);
|
|
res = -1;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
// 20181017 AC
|
|
public static void log(string message)
|
|
{
|
|
string logFile = string.Concat(logPath, "log.txt");
|
|
message = "[" + DateTime.Now.ToLongTimeString() + "]" + message;
|
|
|
|
using (var f = new StreamWriter(logFile, true))
|
|
{
|
|
f.WriteLine(message);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|