ZerOne
ZerOne

Reputation: 1326

WinSCP C# first use

I installed WinSCP on my PC and want to get a connection to another server through a C# Console Application.

 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();
        }
    }
}

But if I run the .exe, the application crashs even before the first console.writeline appears.. Any ideas what I'm doing wrong?

Update: An alert pops up which says: WINSCP_SFTP has stopped working.. then in the cmd line a text appears: Unhandled Exception.. I tried to make a try..catch around my whole code but it also doesn't catch the error

Error that occurs(Picture from web, not a screenshot of my application): enter image description here

Upvotes: 2

Views: 37217

Answers (2)

Rajkumar
Rajkumar

Reputation: 121

//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;
        }     
    }
}

Upvotes: 2

BLoB
BLoB

Reputation: 9725

Try something more like this (this comes from a windows web service).

winscp.exe must be in the root directory of the application.

EDIT: see 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. " Try putting the .exe in your app folder.

To 'merge the winSCP dll into your exe have a read of 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);
}

Upvotes: 2

Related Questions