我在我的PC上安装了WinSCP,并希望通过C#控制台应用程序连接到另一台服务器。
using WinSCP;
namespace WINSCP_SFTP
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("test");
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "hostname",
UserName = "user",
Password = "password"
};
using (Session session = new Session())
{
session.ExecutablePath = @"C:\Program Files\WinSCP";
session.Open(sessionOptions);
Console.WriteLine(session.Opened);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
但是如果我运行.exe,应用程序甚至会在第一个console.writeline出现之前崩溃..任何想法我做错了什么?
更新: 弹出一个警告说:WINSCP_SFTP已停止工作..然后在cmd行中出现一个文本:Unhandled Exception ..我试图围绕我的整个代码进行try..catch,但它也没有捕获错误
发生错误(来自网络的图片,而非我的应用程序的屏幕截图):
答案 0 :(得分:1)
尝试更像这样的东西(这来自Windows Web服务)。
winscp.exe必须位于应用程序的根目录中。
编辑:请参阅winscp.net/eng/docs/library_install" WinSCP .NET程序集与WinSCP winscp.exe交互。默认情况下,它会在存储程序集的同一文件夹中查找winscp.exe。因此,您应该将包解压缩到安装/提取WinSCP的同一文件夹中。您还可以将所有二进制文件winscp.exe和winscpnet.dll复制到单独的文件夹中。 "尝试将.exe放在您的app文件夹中。
要将winSCP dll合并到您的exe中,请阅读Embedding DLLs in a compiled executable
using WinSCP;
try
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = EdiConfiguration.FtpIpAddressOrHostName,
UserName = EdiConfiguration.FtpUserName,
Password = EdiConfiguration.FtpPassword,
SshHostKeyFingerprint = EdiConfiguration.SshHostKeyFingerprint,
PortNumber = EdiConfiguration.FtpPortNumber
};
using (Session session = new Session())
{
session.Open(sessionOptions);
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
transferOptions.ResumeSupport.State = TransferResumeSupportState.Off;
// Download the files in the OUT directory.
TransferOperationResult transferOperationResult = session.GetFiles(EdiConfiguration.FtpDirectory, EdiConfiguration.IncommingFilePath, false, transferOptions);
// Check and throw if there are any errors with the transfer operation.
transferOperationResult.Check();
// Remove files that have been downloaded.
foreach (TransferEventArgs transfer in transferOperationResult.Transfers)
{
RemovalOperationResult removalResult = session.RemoveFiles(session.EscapeFileMask(transfer.FileName));
if (!removalResult.IsSuccess)
{
eventLogUtility.WriteToEventLog("There was an error removing the file: " + transfer.FileName + " from " + sessionOptions.HostName + ".", EventLogEntryType.Error);
}
}
}
}
catch (SessionLocalException sle)
{
string errorDetail = "WinSCP: There was an error communicating with winscp process. winscp cannot be found or executed.";
errorDetail += Environment.NewLine + "Message:" + sle.Message;
errorDetail += Environment.NewLine + "Target Site:" + sle.TargetSite;
errorDetail += Environment.NewLine + "Inner Exception:" + sle.InnerException;
errorDetail += Environment.NewLine + "Stacktrace: " + sle.StackTrace;
eventLogUtility.WriteToEventLog(errorDetail, EventLogEntryType.Error);
}
catch (SessionRemoteException sre)
{
string errorDetail = "WinSCP: Error is reported by the remote server; Local error occurs in WinSCP console session, such as error reading local file.";
errorDetail += Environment.NewLine + "Message:" + sre.Message;
errorDetail += Environment.NewLine + "Target Site:" + sre.TargetSite;
errorDetail += Environment.NewLine + "Inner Exception:" + sre.InnerException;
errorDetail += Environment.NewLine + "Stacktrace: " + sre.StackTrace;
eventLogUtility.WriteToEventLog(errorDetail, EventLogEntryType.Error);
}
catch (Exception ex)
{
eventLogUtility.WriteToEventLog("Error in ProcessEdi() while downloading EDI files via FTP: Message:" + ex.Message + "Stacktrace: " + ex.StackTrace, EventLogEntryType.Error);
}
答案 1 :(得分:0)
//Using WinSCP to upload and download files
using System;
using System.Configuration;`
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using log4net;
using log4net.Config;
using WinSCP;
namespace SynchSubscriptions
{
public class Program
{
// Initialize logger
private static readonly ILog Logger = LogManager.GetLogger(typeof(Program));
public static void Main(string[] args)
{
Download();
UploadFile();
}
public static void Download()
{
try
{
string ftpurl = ConfigurationManager.AppSettings["FTPUrl"];
string ftpusername = ConfigurationManager.AppSettings["FTPUsername"];
string ftppassword = ConfigurationManager.AppSettings["FTPPassword"];
string ftpSSHFingerPrint = ConfigurationManager.AppSettings["SSHFingerPrint"];
string ftpfilepath = ConfigurationManager.AppSettings["FtpFilePath"];
string Download = ConfigurationManager.AppSettings["Download"];
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = ftpurl,
UserName = ftpusername,
Password = ftppassword,
PortNumber = 22,
SshHostKeyFingerprint = ftpSSHFingerPrint
};
using (Session session = new Session())
{
session.SessionLogPath = "";
session.Open(sessionOptions);
RemoteDirectoryInfo directory = session.ListDirectory("/Export/");
foreach (RemoteFileInfo fileInfo in directory.Files)
{
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
transferOptions.FilePermissions = null;
transferOptions.PreserveTimestamp = false;
transferOptions.ResumeSupport.State = TransferResumeSupportState.Off;
TransferOperationResult transferResult;
transferResult = session.GetFiles("/Export/" + fileInfo.Name, Download, false, transferOptions);
transferResult.Check();
}
}
}
catch (Exception ex)
{
}
}
private static bool UploadFile()
{
bool success = false;
string sourcefilepath = "Input File Path";
try
{
string ftpurl = ConfigurationManager.AppSettings["FTPUrl"];
string ftpusername = ConfigurationManager.AppSettings["FTPUsername"];
string ftppassword = ConfigurationManager.AppSettings["FTPPassword"];
string ftpSSHFingerPrint = ConfigurationManager.AppSettings["SSHFingerPrint"];
string ftpfilepath = ConfigurationManager.AppSettings["FtpFilePath"];
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = ftpurl,
UserName = ftpusername,
Password = ftppassword,
SshHostKeyFingerprint = ftpSSHFingerPrint
};
string filename = Path.GetFileName(sourcefilepath);
string ftpfullpath = ftpurl + "/" + filename;
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult = session.PutFiles(sourcefilepath, ftpfilepath, false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
success = true;
}
}
// Delete the file after uploading
if (File.Exists(sourcefilepath))
{
File.Delete(sourcefilepath);
}
}
catch (Exception ex)
{
}
return success;
}
}
}