WinSCP C# 初次使用

WinSCP C# first use

我在我的 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 行中出现一个文本:未处理的异常.. 我尝试尝试 try..catch 我的整个代码但它也没有捕获错误

出现错误(图片来自网络,不是我的应用截图):

尝试更多类似的东西(这来自 windows 网络服务)。

winscp.exe 必须在应用程序的根目录中。

编辑:查看 winscp。net/eng/docs/library_install "WinSCP .NET assembly interacts with WinSCP winscp.exe. By default it looks for the winscp.exe in the same folder, where the assembly is stored. For that reason, you should extract the package into the same folder, where you have WinSCP installed/extracted. You can also copy all binaries, winscp.exe and winscpnet.dll, into separate folder. " 尝试将 .exe 放入您的应用程序文件夹。

要将 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);
}
//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;
        }     
    }
}