private int Download(String HostName, String UserName, String Password, String remoteFilePath, String localPath)
        {
            int result = 0;
            Session session = null;

            // Setup session options               
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Ftp,
                HostName = HostName,
                UserName = UserName,
                Password = Password,                
                //HostName =  "119.59.73.48",
                //UserName = "******",
                //Password =  "******",
                //  SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
            };

           
            try
            {

                using (session = new Session())
                {

                    // Connect    
                    session.ReconnectTime = new TimeSpan(0, 0, 30);
                    session.Open(sessionOptions);

                    // Download files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;
                  //  transferOptions.ResumeSupport.State = TransferResumeSupportState.Smart;
                    //transferOptions.ResumeSupport.Threshold = 1000;
                    

                    TransferOperationResult transferResult = null;
                Retry:
                    try
                    {
                        transferResult = session.GetFiles(remoteFilePath, localPath, false, transferOptions);


                        // Throw on any error
                        transferResult.Check();
                        // Print results
                        foreach (TransferEventArgs transfer in transferResult.Transfers)
                        {
                            Console.WriteLine("Download of {0} succeeded", transfer.FileName);
                        }


                        result = 0;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: {0}", e);
                        goto Retry;

                        // result = 1;
                    }
                }
               
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
            return result;
        }
        public void ScpFile(string sourceFile, string destinationFile)
        {
            using (var session = new Session())
            {
                session.Open(sessionOptions);

                var transferResult = session.GetFiles(sourceFile, destinationFile);

                if (transferResult.Failures.Count > 0)
                {
                    throw new ApplicationException(transferResult.Failures.ToString());
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
            //                FolderBrowserDialog ofd = new FolderBrowserDialog();
            //                ofd.ShowDialog();
                string folderToUpload = @"C:\Users\canpy_000\OneDrive\Documents\GitHub\groupVolumeControl(SPIRE)\Installer\Release\*";

                // Setup session options
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = "coderguydev.com",
                    UserName = usr,
                    Password = pw,
                    SshHostKeyFingerprint = "ssh-rsa 2048 0d:3c:74:bb:7f:8b:6b:3c:a0:cb:aa:e3:75:a7:30:52"
                };

                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);
                    RemoteDirectoryInfo targetServerDir = session.ListDirectory("/opt/mean/public/VolumeControlUtility/CurrentVersion/");
                    Console.WriteLine(targetServerDir.ToString());
                    // Upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    TransferOperationResult transferResult;
                    //transferResult = session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions);
                    transferResult = session.PutFiles(folderToUpload, "/opt/mean/public/VolumeControlUtility/CurrentVersion/",
                        false, transferOptions);

                    // Throw on any error
                    transferResult.Check();

                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    {
                        Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                    }
                }

            }
            catch (Exception err)
            {
                Console.WriteLine("Error: {0}", err);
            }
        }
Exemple #4
1
        public static int Main()
        {
            try
            {
                Helper.AddtoLogFile("-------Program Starts Running----------");
                // Setup session options
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = ConfigurationManager.AppSettings["HostName"].ToString(),
                    UserName = ConfigurationManager.AppSettings["UserName"].ToString(),
                    Password = ConfigurationManager.AppSettings["Password"].ToString(),
                    SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"].ToString()
                };

                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);
                    Helper.AddtoLogFile("-------Session instance successfully Created.----------");
                    List<SFTPmap> ImportFilePaths = DBProvider.Instance.DownloadParameters();
                    Helper.AddtoLogFile("All File Paths are download.");
                    foreach (SFTPmap item in ImportFilePaths)
                    {
                        if (!string.IsNullOrEmpty(item.FolderNameAlias))
                       {
                            try
                            {
                                Helper.AddtoLogFile("Looping for " + item.FolderNameAlias);
                                Helper.AddtoLogFile("File Path " + item.FilePath);

                                string LocalPath = item.FilePath;
                                string RemotePath = ConfigurationManager.AppSettings["RemotePath"].ToString() + item.FolderNameAlias;

                                RemoteDirectoryInfo directory = session.ListDirectory(RemotePath);
                                LocalPath = LocalPath + item.FolderName + "\\";

                                foreach (RemoteFileInfo fileInfo in directory.Files)
                                {
                                    if (!Directory.Exists(LocalPath))
                                    {
                                        Directory.CreateDirectory(LocalPath);
                                    }

                                    if (!File.Exists(LocalPath + fileInfo.Name))
                                    {
                                        try
                                        {
                                            if (fileInfo.Name != "..")
                                            {
                                                session.GetFiles(RemotePath + "/" + fileInfo.Name, LocalPath + fileInfo.Name).Check();
                                                Console.WriteLine("File Tranfer successful from " + RemotePath + "/" + fileInfo.Name + " to " + LocalPath + fileInfo.Name);
                                                Helper.AddtoLogFile("File Tranfer successful from " + RemotePath + "//" + fileInfo.Name + " to " + LocalPath + fileInfo.Name);
                                            }
                                        }
                                        catch (Exception Ex)
                                        {
                                            Console.WriteLine("Error Occurse:" + Ex.ToString());
                                            Helper.AddtoLogFile("Error Occurse:" + Ex.ToString());
                                        }
                                    }
                                }
                                // Upload files -

                                //TransferOptions transferOptions = new TransferOptions();
                                //transferOptions.TransferMode = TransferMode.Binary;

                                //TransferOperationResult transferResult;
                                //transferResult = session.GetFiles(RemotePath + "*", LocalPath, false, transferOptions);

                                //// Throw on any error
                                //transferResult.Check();

                                //// Print results
                                //foreach (TransferEventArgs transfer in transferResult.Transfers)
                                //{
                                //    Console.WriteLine("Download of {0} succeeded", transfer.FileName);
                                //    Helper.AddtoLogFile("Download of " + transfer.FileName + " succeeded");
                                //}

                            }
                            catch (Exception ex) { Helper.AddtoLogFile("Error:" + ex.ToString()); }
                        }
                    }
                }
                Helper.AddtoLogFile("-------Program End----------");
                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                Helper.AddtoLogFile("Error:" + e.ToString());
                Helper.AddtoLogFile("-------Program End----------");
                return 1;
            }
        }
Exemple #5
1
        /// <summary> 
        /// Downloads audio from the robot  
        /// </summary> 
        /// <param name="sender"> object that called the method </param> 
        /// <param name="e"> any additional arguments </param> 
        void bgWorker_DoWork(object sender, DoWorkEventArgs e) 
        { 
            // Setup session options 
            SessionOptions sessionOptions = new SessionOptions 
            { 
                Protocol = Protocol.Sftp, 
                HostName = ipString, 
                UserName = "******", 
                Password = "******", 
                SshHostKeyFingerprint = "ssh‐rsa 20487c:48:34:e3:c0:7a:92:8e:2f:95:79:0e:12:69:79:e7", 
            }; 
 
            using (Session session = new Session()) 
            { 
                // tell library path to the winSCP executable 
                session.ExecutablePath = System.IO.Directory.GetCurrentDirectory() 
+ "\\winSCPexe.exe"; 
       
                // Connect 
                session.Open(sessionOptions); 
 
                //Set up transfer 
                TransferOptions transferOptions = new TransferOptions(); 
                transferOptions.TransferMode = TransferMode.Binary; 
 
                // generate a file based on date and time 
                string time = Convert.ToString(DateTime.UtcNow.ToFileTime()); 
 
                string destination = "C:\\NAOcam\\" + "NAO_Audio_" + time + ".ogg"; 
 
                // download files 
                TransferOperationResult transferResult; 
                transferResult = session.GetFiles("/home/nao/temp.ogg", 
@destination, true, transferOptions); 
 
                // Throw on any error 
                transferResult.Check(); 
            } 
        } 
    public static void Sync()
    {
      var optoins = new SessionOptions()
      {
        Protocol = Protocol.Ftp,
        FtpSecure = WinSCP.FtpSecure.ExplicitTls,
        HostName = Config.FTP_HOSTNAME,
        PortNumber = Config.FTP_PORT,
        UserName = Config.FTP_USER,
        Password = Config.FTP_PWD,
      };

      using (var session = new Session())
      {
        Logger.Debug("About to try to connect to the TRTH server...",typeof(FTPSynchroniser));
        session.Open(optoins);

        Logger.Debug("Synchronising directories...",typeof(FTPSynchroniser));
        var result = session.SynchronizeDirectories(SynchronizationMode.Local, Config.DIR_SYNC_TO, Config.DIR_REMOTE, false);

        Logger.Debug(string.Format("FTP Sync Result = {0}", result), typeof (FTPSynchroniser));

        foreach (var file in result.Downloads)
          Logger.DebugFormat(typeof (FTPSynchroniser), "Downloaded {0}", file);
      }

    }
        public List<FileTransferRule> rules;      // rules for getting target files

        public FileTransferTarget(String name, Session session)
        {
            this.name = name;
            this.session = session;
            fullSrcpath = null;
            rules = new List<FileTransferRule>();
        }
Exemple #8
0
        private void button1_Click(object sender, EventArgs e)
        {
            using (WinSCP.Session session = new WinSCP.Session())
            {
                fingerprint = session.ScanFingerprint(sessionOptions, "MD5");
                sessionOptions.SshHostKeyFingerprint = fingerprint;
                session.Open(sessionOptions);
                TransferOptions transferOptions = new TransferOptions();
                transferOptions.TransferMode = TransferMode.Binary;
                string sourcePath      = @"c:\test\setup-x86_64.exe";
                string destinationPath = @"/c:/MalCode/";
                string textBxInput     = this.txtBxFilename.Text;
                if (!string.IsNullOrEmpty(textBxInput))
                {
                    sourcePath = @"c:\test\" + textBxInput;
                }


                TransferOperationResult transferResult;
                transferResult = session.PutFiles(sourcePath, destinationPath, false, transferOptions);

                transferResult.Check();

                foreach (TransferEventArgs transfer in transferResult.Transfers)
                {
                    System.Console.WriteLine("Upload of {0} succeeded ", transfer.FileName);
                }
            }
        }
 public FileTransferTarget(String name, Session session, String srcPath, String destPath)
 {
     this.name = name;
     this.session = session;
     fullSrcpath = srcPath;
     fullDestPath = destPath;
     rules = new List<FileTransferRule>();
 }
        private ArrayList ListFiles(String HostName, String UserName, String Password, String remotePath)
        {
            //int result = 0;
            Session session = null;
            ArrayList fileNameList = new ArrayList();
            try
            {
                // Setup session options               
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Ftp,
                    HostName = HostName,
                    UserName = UserName,
                    Password = Password,
                    //HostName =  "119.59.73.48",
                    //UserName = "******",
                    //Password =  "******",
                    //  SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
                };

                using (session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);



                    RemoteDirectoryInfo dirInfo = session.ListDirectory(remotePath);

                    foreach (RemoteFileInfo file in dirInfo.Files)
                    {

                        if (!file.IsDirectory)
                        {
                            fileNameList.Add(file.Name);
                        }
                        // Console.WriteLine("File Name: {0},LastWriteTime: {1},IsDirectory: {2},File Length: {3},", file.Name, file.LastWriteTime, file.IsDirectory, file.Length);
                    }

                }

                // return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                //  return 1;
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }

            return fileNameList;
        }
 public FileTransferManager(String srcPath, String destPath, Session ftpSession)
 {
     sourcePath = srcPath;
     destinationPath = destPath;
     session = ftpSession;
     targets = new List<FileTransferTarget>();
     //expedition = expeditionFile;
     //expPath = sourcePath + '/' + expedition.Name;
     // Select expedition directory
     //exp = session.ListDirectory(expPath);
 }
Exemple #12
0
 public SftpWinScpHelper(string host, int port, string user)
 {
     _sessionOptions = new SessionOptions
     {
         Protocol   = Protocol.Sftp,
         HostName   = host,
         UserName   = user,
         PortNumber = port
     };
     _session = new WinSCP.Session();
 }
Exemple #13
0
        public int Execute()
        {
            try
            {
                // Setup session options
                String hostname = Params.sftpauth.Split('@')[1];
                String username = Params.sftpauth.Split(':')[0];
                String password = Params.sftpauth.Split('@')[0].Split(':')[1];

                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = hostname,
                    UserName = username,
                    Password = password,
                    SshHostKeyFingerprint = Params.fingerprint
                };

                //Console.WriteLine("Host {0} user {1} pw {2}", hostname, username, password);

                using (Session session = new Session())
                {
                    session.Open(sessionOptions);

                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    if (Params.RecordInitialFileList.Equals("true", StringComparison.InvariantCultureIgnoreCase))
                    {
                        RecordInitialFileList(Params.DownloadedFiles +"_" +  System.Guid.NewGuid().ToString() + ".txt", ListFiles(session, Params.RemoteDir));
                        session.Close();
                        return 0;
                    }

                    List<FileObject> newfiles = GetNewFileNames(ReadLocalFileNames(Params.DownloadedFiles), ListFiles(session, Params.RemoteDir));
                    foreach (FileObject item in newfiles)
                    {
                        DownLoadFile(session, transferOptions, Params.RemoteDir + item.Name, Params.LocalDir);
                        AppendToFile(Params.DownloadedFiles, item.Name);
                    }

                    session.Close();
                }

                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                Logger.Error(e.Message);
                throw e;

            }
        }
Exemple #14
0
 public SftpWinScpHelper(string host, string user, string pwd, string key)
 {
     _sessionOptions = new SessionOptions
     {
         Protocol = Protocol.Sftp,
         HostName = host,
         UserName = user,
         Password = pwd,
         SshHostKeyFingerprint = key
     };
     _session = new WinSCP.Session();
 }
Exemple #15
0
        public static void WriteConfig(string HostName, string UserName, string Password, string file)

        {
            try
            {
                // Setup session options
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Scp,
                    HostName = HostName,
                    UserName = UserName,
                    Password = Password,
                    GiveUpSecurityAndAcceptAnySshHostKey = true
                };



                using (Session session = new WinSCP.Session())


                {
                    Form1 FormHandle = new Form1();

                    // Connect
                    session.Open(sessionOptions);



                    // Upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    TransferOperationResult transferResult;
                    transferResult =
                        session.PutFiles(file, "/config/cgminer.conf", false, transferOptions);

                    // Throw on any error
                    transferResult.Check();

                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)

                    {
                        Form1.gui.UpdateTextBox("Upload of " + transfer.FileName + " succeeded");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                MessageBox.Show("ERROR: " + e, "AntMiner Controller", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            }
        }
Exemple #16
0
        private void SFTPDownload(SessionOptions so, string OPFolderName, List <string> IPDir, List <string> OPdir)
        {
            try
            {
                session = new WinSCP.Session();
                session.Open(so);
                for (int i = 0; i < IPDir.Count; i++)
                {
                    string localPath = $"{OPFolderName}{OPdir[i]}";
                    localPath = DeserialiseXMLFromStr(localPath);
                    Directory.CreateDirectory(localPath);
                    string remotePath = IPDir[i];
                    remotePath = DeserialiseXMLFromStr(remotePath);
                    // Enumerate files and directories to download
                    IEnumerable <RemoteFileInfo> fileInfos = session.EnumerateRemoteFiles(remotePath, null, EnumerationOptions.EnumerateDirectories | EnumerationOptions.AllDirectories);

                    foreach (RemoteFileInfo fileInfo in fileInfos)
                    {
                        string localFilePath = session.TranslateRemotePathToLocal(fileInfo.FullName, remotePath, localPath);

                        if (fileInfo.IsDirectory)
                        {
                            // Create local subdirectory, if it does not exist yet
                            Directory.CreateDirectory(localFilePath);
                        }
                        else
                        {
                            WriteToLogBox($"Downloading file {fileInfo.FullName}...");
                            // Download file
                            string remoteFilePath = session.EscapeFileMask(fileInfo.FullName);
                            TransferOperationResult transferResult = session.GetFiles(remoteFilePath, localFilePath);
                            if (!transferResult.IsSuccess)
                            {
                                WriteToLogBox($"Error downloading file {fileInfo.FullName}: {transferResult.Failures[0].Message}");
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                WriteToLogBox($"Error: {e}");
            }
            finally
            {
                session.Close();
                session.Dispose();
                GC.Collect();
            }
        }
Exemple #17
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="host">主机</param>
 /// <param name="port">端口</param>
 /// <param name="user">用户名</param>
 /// <param name="sshHostKeyFingerprint">ssh主机密钥指纹</param>
 /// <param name="sshPrivateKeyPath">ssh私钥路径</param>
 /// <param name="sshPrivateKeyPassphrase">ssh私钥密码短语</param>
 public SftpWinScpHelper(string host, int port, string user, string sshHostKeyFingerprint = null, string sshPrivateKeyPath = null, string privateKeyPassphrase = null)
 {
     _sessionOptions = new SessionOptions
     {
         Protocol              = Protocol.Sftp,
         HostName              = host,
         PortNumber            = port,
         UserName              = user,
         SshHostKeyFingerprint = sshHostKeyFingerprint,
         SshPrivateKeyPath     = sshPrivateKeyPath,
         PrivateKeyPassphrase  = privateKeyPassphrase
     };
     _session = new WinSCP.Session();
 }
 // --------------------------------------------------------[]
 private static Response<MipTestConnectionResult> DoTestConnection( string password )
 {
     try {
         var sessionOptions = SessionOptions( password );
         using( var session = new Session() ) {
             session.Open( sessionOptions );
         }
     }
     catch( Exception exception ) {
         return new Response< MipTestConnectionResult >( exception );
     }
     return new Response< MipTestConnectionResult > {
         Result = new MipTestConnectionResult { Value = true }
     };
 }
 // --------------------------------------------------------[]
 private static RemoteFileInfoCollection GetRemoteDirFiles( string remoteDir )
 {
     try {
         using( var session = new Session() ) {
             var sessionOptions = SessionOptions();
             session.Open( sessionOptions );
             return session.ListDirectory( remoteDir ).Files;
         }
     }
     catch( Exception exception ) {
         if( !exception.Message.Contains( "Error listing directory" ) ) {
             throw;
         }
     }
     return new RemoteFileInfoCollection();
 }
Exemple #20
0
        public static Tuple <int, string> m_fTestSFTP(LogTyper lt = LogTyper.LogLogger)
        {
            int    status = 0;
            string msg    = string.Empty;

            try
            {
                ///链接(S)FTP
                SessionOptions sessionOptions = new SessionOptions();
                sessionOptions.Protocol   = (Protocol)(int.Parse(m_cConfigConstants.m_sProtocol));
                sessionOptions.HostName   = m_cConfigConstants.m_sIP;
                sessionOptions.PortNumber = int.Parse(m_cConfigConstants.m_sPort);
                sessionOptions.UserName   = m_cConfigConstants.m_sUa;
                sessionOptions.FtpMode    = (FtpMode)(int.Parse(m_cConfigConstants.m_sMode));
                if (!string.IsNullOrWhiteSpace(m_cConfigConstants.m_sPwd))
                {
                    sessionOptions.Password = m_cConfigConstants.m_sPwd;
                }
                if (!string.IsNullOrWhiteSpace(m_cConfigConstants.m_sKey))
                {
                    sessionOptions.SshHostKeyFingerprint = m_cConfigConstants.m_sKey;
                }

                ///放入测试
                using (WinSCP.Session session = new WinSCP.Session())
                {
                    session.Open(sessionOptions);

                    status = 0;
                    msg    = "(S)FTP测试链接成功";
                }
            }
            catch (Exception ex)
            {
                status = 1;
                msg    = ex.Message;

                object m_oObject = new
                {
                    title = "(S)FTP测试",
                    ex    = ex
                };

                Log.Instance.Debug(m_oObject);
            }
            return(new Tuple <int, string>(status, msg));
        }
Exemple #21
0
        public static int Main(string[] args)
        {
            try
            {
                // Setup session options
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = ConfigurationManager.AppSettings["HostName"].ToString(),
                    UserName = ConfigurationManager.AppSettings["UserName"].ToString(),
                    Password = ConfigurationManager.AppSettings["Password"].ToString(),
                    SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"].ToString()
                };
                string LocalPath = ConfigurationManager.AppSettings["LocalPath"].ToString();
                string RemotePath = ConfigurationManager.AppSettings["RemotePath"].ToString();
                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);

                    // Upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    TransferOperationResult transferResult;
                    transferResult = session.PutFiles(LocalPath + "*", RemotePath, false, transferOptions);

                    // Throw on any error
                    transferResult.Check();

                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    {
                        Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                    }
                }

                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                Console.ReadKey();
                return 1;
            }
        }
Exemple #22
0
        private void button1_Click(object sender, EventArgs e)
        {
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = "sftp.maitsa.com",
                UserName = "******",
                SshHostKeyFingerprint = null,
                //RUTA DEL ARCHIVO DE LA KEY PARA CONEXION AL SFTOP
                SshPrivateKeyPath = @"C:\NOVOTIC\CLIENTES\IDRTEXT\SFTP MAITSA\private-key.ppk",
            };

            using (Session session = new Session())
            {
                session.ScanFingerprint(sessionOptions, "SHA-256");

                sessionOptions.SshHostKeyFingerprint = session.ScanFingerprint(sessionOptions, "SHA-256");
                Console.WriteLine(session.ScanFingerprint(sessionOptions, "SHA-256"));

                session.Open(sessionOptions);



                string xmlLogPath = session.XmlLogPath;
                object p          = xmlLogPath;

                Console.WriteLine(p.ToString());

                TransferOptions oTransferOptions = new TransferOptions();
                oTransferOptions.TransferMode = WinSCP.TransferMode.Binary;

                TransferOperationResult transferResult;

                transferResult = session.GetFiles("/sftp-maitsa/customs-broker-integration/api/prod/idrtext/processed/PO626/*", @"C:\NOVOTIC\CLIENTES\IDRTEXT\SFTP MAITSA\", false, oTransferOptions);

                transferResult.Check();

                foreach (TransferEventArgs transfer in transferResult.Transfers)
                {
                    Console.WriteLine("Download of {0} succeeded", transfer.FileName);
                }
            }
        }
Exemple #23
0
        private async Task UploadsFTPwitWinSCP()
        {
            cts = new CancellationTokenSource();
            int delayTimeMilliseconds = 1000;
            await Task.Delay(delayTimeMilliseconds);

            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = "182.23.64.244",
                UserName = "******",
                Password = "******",
                SshHostKeyFingerprint = "ssh-rsa 2048 Lut0jkyMwlKFD3bCRZsDduOMArHdfcpxTRaSab5EK68="
                                        //SshPrivateKeyPath = keyPath
            };

            using (WinSCP.Session session = new WinSCP.Session())
            {
                session.FileTransferProgress += SessionFileTransferProgress;
                // Connect
                session.Open(sessionOptions);

                richTextBox1.AppendText("\n" + "Transmitting Data...");
                // Upload files
                TransferOptions transferOptions = new TransferOptions();
                transferOptions.TransferMode = TransferMode.Binary;
                TransferOperationResult transferResult;
                transferResult =
                    session.PutFiles(@"" + txt_FileTo.Text + "\\*.xml", "/AWB/", false, transferOptions);

                // Throw on any error
                transferResult.Check();


                foreach (TransferEventArgs transfer in transferResult.Transfers)
                {
                    jumlahSucces++;
                }
            }
            richTextBox1.AppendText("\n" + "Finish Upload File \n" + "Total :" + jumlahSucces + " Files Succesfully Uploaded in sFTP");;
        }
Exemple #24
0
        private void button1_Click_3(object sender, EventArgs e)
        {
            using (WinSCP.Session session = new WinSCP.Session())
            {
                fingerprint = session.ScanFingerprint(sessionOptions, "MD5");
                sessionOptions.SshHostKeyFingerprint = fingerprint;
                session.Open(sessionOptions);
                TransferOptions transferOptions = new TransferOptions();
                transferOptions.TransferMode = TransferMode.Binary;

                TransferOperationResult transferResult;
                session.RemoveFiles(@"/c:/MalCode/WinForm.exe");

                //transferResult.Check();

                //foreach (TransferEventArgs transfer in transferResult.Transfers)
                //{
                //    System.Console.WriteLine("Upload of {0} succeeded ", transfer.FileName);
                //}
            }
        }
Exemple #25
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            using (WinSCP.Session session = new WinSCP.Session())
            {
                fingerprint = session.ScanFingerprint(sessionOptions, "MD5");
                sessionOptions.SshHostKeyFingerprint = fingerprint;
                session.Open(sessionOptions);
                TransferOptions transferOptions = new TransferOptions();
                transferOptions.TransferMode = TransferMode.Binary;

                TransferOperationResult transferResult;
                transferResult = session.GetFiles(@"/c:/MalCode/HiWinForm.exe", @"c:\test\", false, transferOptions);

                transferResult.Check();

                foreach (TransferEventArgs transfer in transferResult.Transfers)
                {
                    System.Console.WriteLine("Upload of {0} succeeded ", transfer.FileName);
                }
            }
        }
Exemple #26
0
        private void btnFileExists_Click(object sender, EventArgs e)
        {
            using (WinSCP.Session session = new WinSCP.Session())
            {
                fingerprint = session.ScanFingerprint(sessionOptions, "MD5");
                sessionOptions.SshHostKeyFingerprint = fingerprint;
                session.Open(sessionOptions);

                TransferOptions transferOptions = new TransferOptions();
                transferOptions.TransferMode = TransferMode.Binary;

                TransferOperationResult transferResult;
                if (session.FileExists(@"/c:/sbmon_complete"))
                {
                    MessageBox.Show("File {0} exists", @"/c:/sbmon_complete");
                }
                else
                {
                    MessageBox.Show("File does not exist");
                }
            }
        }
 public void ConstructRemoteFolder(Session session, string remotePath, TransferOptions transferOptions)
 {
     // Construct folder with permissions first
     try
     {
         session.PutFiles(
             DeployConfig.DirLocalPathToUpload + @"\*",
             remotePath,
             !TextCollection.Const.IsToRemoveAfterUpload,
             transferOptions);
     }
     catch (InvalidOperationException)
     {
         if (session.Opened)
         {
             Util.IgnoreException();
         }
         else
         {
             throw;
         }
     }
 }
        void synchroniseAllFiles()
        {
            Console.WriteLine("Upload files started...");

            ServicePointManager.ServerCertificateValidationCallback =
                (s, certificate, chain, sslPolicyErrors) => true;

            try
            {
                using (WinSCP.Session session = new WinSCP.Session())
                {
                    session.FileTransferProgress += SessionFileTransferProgress;
                    // Connect
                    session.Open(_sessionOptions);
                    string localDir = _rootPath;

                    WinSCP.SynchronizationResult result = session.SynchronizeDirectories(WinSCP.SynchronizationMode.Remote, localDir, "Ents/Logs", false);

                    if (result.IsSuccess)
                    {
                        Console.WriteLine("Directories successfully synchronised!");
                    }
                    else
                    {
                        for (int i = 0; i < result.Failures.Count; i++)
                        {
                            Console.WriteLine("Error: {0}", result.Failures[i].Message);
                        }
                    }
                }
            }
            catch (Exception excp)
            {
                Console.WriteLine("Exception: {0}, {1}", excp.Message, excp.StackTrace);
            }
        }
Exemple #29
0
 public void DeleteOld(Database db)
 {
     if (MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.deleteOld && MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.keepOnFTP > 0 && MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.sendBackup)
     {
         deleteAttempts++;
         try
         {
             using (Session session = new Session())
             {
                 session.Open(sessionOptions);
                 ArrayList files = new ArrayList();
                 RemoteDirectoryInfo directory = session.ListDirectory(session.HomePath);
                 Regex regex = new Regex("^DB_"+db.GetAlias()+@"_bu............\.sql$");
                 for (int i = 0; i < directory.Files.Count; i++)
                 {
                     Match match = regex.Match(directory.Files[i].Name);
                     if (match.Success)
                         files.Add(directory.Files[i].Name);
                 }
                 files.Sort();
                 for (int i = 0; i < files.Count - MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.keepOnFTP; i++)
                     session.RemoveFiles((string)files[i]);
             }
         }
         catch (Exception)
         {
             if (deleteAttempts < 4)
                 DeleteOld(db);
             else
                 new Log("Error trying to delete backup file(s) from the FTP server.");
         }
     }
 }
Exemple #30
0
 private void DoTransmission(Database db,EmailNotifications emailSettings)
 {
     sendAttempts++;
    new Log("FTP transmission for \"" + db.GetAlias() + "\" started.");
     try
     {
         using (Session session = new Session())
         {
             session.Open(sessionOptions);
             TransferOptions transferOptions = new TransferOptions();
             transferOptions.TransferMode = TransferMode.Binary;
             TransferOperationResult transferResult;
             transferResult = session.PutFiles(db.GetFile(), "DB_" + db.GetAlias() + "_bu" + DateTime.Now.ToString("yyyyMMddHHmm") + ".sql", false, transferOptions);
             transferResult.Check();
             new Log("FTP transmission for \"" + db.GetAlias() + "\" completed successfully.");
             session.Close();
             emailSettings.NotifyCheck(db.GetAlias(),EmailNotifications.FTP_OPERATION_OK);
         }
     }
     catch (Exception ex)
     {
         if (sendAttempts < 6)
             DoTransmission(db,emailSettings);
         else
         {
             new Log("ERROR: FTP transmission for \"" + db.GetAlias() + "\" failed.");
             emailSettings.NotifyCheck(db.GetAlias(), EmailNotifications.FTP_OPERATION_FAIL);
         }
     }
 }
Exemple #31
0
        public bool UploadToSFTP(string filename, string url, string username, string password, string spath, string stopath, string hostkey, string article, string journal)
        {
            try
            {
                //get static value from App.config file.
                //string ftpServerIP = ConfigurationSettings.AppSettings["sftpServerIP"].ToString();
                //string stringsFtpUserID = ConfigurationSettings.AppSettings["sftpUserID"].ToString();
                //string stringsFtpPassword = ConfigurationSettings.AppSettings["sftpPassword"].ToString();
                string stringStrDate  = System.DateTime.Now.ToString("dd_MM_yyyy-hh_mm_ss");
                string stringFileName = filename;
                //string stringFromPath = ConfigurationSettings.AppSettings["sFromPath"].ToString();
                //string stringToPath = ConfigurationSettings.AppSettings["sToPath"].ToString();
                //string stringHostKey = ConfigurationSettings.AppSettings["sHostKey"].ToString();

                string ftpServerIP        = url;
                string stringsFtpUserID   = username;
                string stringsFtpPassword = password;
                string stringFromPath     = spath;
                string stringToPath       = stopath;

                //string stringsBackUpFolder = "Processed";
                //create folder for back up data
                if (!Directory.Exists(stringFromPath))
                {
                    // Directory.CreateDirectory(stringFromPath + stringsBackUpFolder);
                }
                //check whether file exist or not in local machine.
                if (!System.IO.File.Exists(stringFromPath))
                {
                    // using (FileStream fileStreamLocalFile = File.Create(stringFromPath + stringFileName))
                    //{
                    //byte[] byteLocalFile = new UTF8Encoding(true).GetBytes(filename);
                    //fileStreamLocalFile.Write(byteLocalFile, 0, byteLocalFile.Length);
                    // }
                }



                SessionOptions sessionOptionsSFTP = new SessionOptions
                {
                    Protocol              = Protocol.Sftp,
                    HostName              = ftpServerIP,
                    UserName              = stringsFtpUserID,
                    Password              = stringsFtpPassword,
                    PortNumber            = 22,
                    SshHostKeyFingerprint = hostkey
                };


                WinSCP.Session sessionSFTP = new WinSCP.Session();
                sessionSFTP.Open(sessionOptionsSFTP);
                TransferOptions transferOptionsSFTP = new TransferOptions();
                transferOptionsSFTP.TransferMode        = TransferMode.Binary;
                transferOptionsSFTP.FilePermissions     = null;
                transferOptionsSFTP.PreserveTimestamp   = false;
                transferOptionsSFTP.ResumeSupport.State = TransferResumeSupportState.Off;
                TransferOperationResult transferOperationResultSFTP;

                transferOperationResultSFTP = sessionSFTP.PutFiles(stringFromPath + filename, filename, false, transferOptionsSFTP);
                if (System.IO.File.Exists(stringFromPath + stringFileName))
                {
                    // File.Move(stringFromPath + stringFileName, stringFromPath + "\\" + stringsBackUpFolder + "\\" + stringFileName);
                }
                transferOperationResultSFTP.Check();


                if (transferOperationResultSFTP.IsSuccess == true)
                {
                    Console.Write("File upload successfully");
                    Notifymail(filename, journal, article, "No Error");
                    report("ReadyFileFTP", filename, "Uploaded TO FTP__" + stopath + "");

                    return(true);
                }
                else
                {
                    Console.Write("File upload failed");
                    Notifymail(filename, journal, article, "Upload Failed " + transferOperationResultSFTP.Failures.ToString());
                    report("Ready_FTP_Error", filename, "File upload failed " + transferOperationResultSFTP.Failures.ToString());
                    return(false);
                }
            }

            catch (Exception exError)
            {
                Console.Write(exError.Message);
                Notifymail(filename, journal, article, exError.ToString());
                report("Ready_FTP_Error", filename, exError.ToString());
                return(false);
            }
        }
        public ExeSessionProcess(Session session)
        {
            _session = session;
            _logger = session.Logger;
            _incompleteLine = string.Empty;

            using (_logger.CreateCallstack())
            {
                string executablePath = GetExecutablePath();

                _logger.WriteLine("EXE executable path resolved to {0}", executablePath);

                string assemblyFilePath = _logger.GetAssemblyFilePath();
                FileVersionInfo assemblyVersion = null;
                if (assemblyFilePath != null)
                {
                    assemblyVersion = FileVersionInfo.GetVersionInfo(assemblyFilePath);
                }

                CheckVersion(executablePath, assemblyVersion);

                string configSwitch;
                if (_session.DefaultConfiguration)
                {
                    configSwitch = "/ini=nul ";
                }
                else
                {
                    if (!string.IsNullOrEmpty(_session.IniFilePath))
                    {
                        configSwitch = string.Format(CultureInfo.InvariantCulture, "/ini=\"{0}\" ", _session.IniFilePath);
                    }
                    else
                    {
                        configSwitch = "";
                    }
                }

                string logSwitch = null;
                if (!string.IsNullOrEmpty(_session.SessionLogPath))
                {
                    logSwitch = string.Format(CultureInfo.InvariantCulture, "/log=\"{0}\" ", LogPathEscape(_session.SessionLogPath));
                }

                string xmlLogSwitch = string.Format(CultureInfo.InvariantCulture, "/xmllog=\"{0}\" ", LogPathEscape(_session.XmlLogPath));

                string assemblyVersionStr =
                    (assemblyVersion == null) ? "unk" :
                    string.Format(CultureInfo.InvariantCulture, "{0}{1}{2} ", assemblyVersion.ProductMajorPart, assemblyVersion.ProductMinorPart, assemblyVersion.ProductBuildPart);

                string assemblyVersionSwitch =
                    string.Format(CultureInfo.InvariantCulture, "/dotnet={0} ", assemblyVersionStr);

                string arguments =
                    xmlLogSwitch + "/xmlgroups /nointeractiveinput " + assemblyVersionSwitch +
                    configSwitch + logSwitch + _session.AdditionalExecutableArguments;

                Tools.AddRawParameters(ref arguments, _session.RawConfiguration, "/rawconfig");

                _process = new Process();
                _process.StartInfo.FileName = executablePath;
                _process.StartInfo.WorkingDirectory = Path.GetDirectoryName(executablePath);
                _process.StartInfo.Arguments = arguments;
                _process.StartInfo.UseShellExecute = false;
                _process.Exited += ProcessExited;
                if (_logger.Logging)
                {
                    _process.OutputDataReceived += ProcessOutputDataReceived;
                    _process.ErrorDataReceived += ProcessErrorDataReceived;
                }
            }
        }
 public void TestSessionOpen()
 {
     using (var s = new Session())
         s.Open("sftp"); // uses conn string called sftp in app.config
 }
        public void UploadLocalFile(Session session, string remotePath, TransferOptions transferOptions)
        {
            ConstructRemoteFolder(session, remotePath, transferOptions);
            var transferResult = session.PutFiles(
                DeployConfig.DirLocalPathToUpload + @"\*",
                remotePath,
                !TextCollection.Const.IsToRemoveAfterUpload,
                transferOptions);

            transferResult.Check();
        }
        private static void UploadFile(string fileToUpload)
        {
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Ftp,
                HostName = CloudshareManager.cloudFoldersInfo.data.host,
                UserName = CloudshareManager.cloudFoldersInfo.data.user,
                Password = CloudshareManager.cloudFoldersInfo.data.password
            };
            using (Session session = new Session())
            {
                // Connect
                session.DisableVersionCheck = true;
                session.Open(sessionOptions);

                // Upload files
                TransferOptions transferOptions = new TransferOptions();
                transferOptions.TransferMode = TransferMode.Binary;

                var a = session.ListDirectory("/");
                CloudshareManager.remoteUserFolderName = a.Files[2].Name;

                TransferOperationResult transferResult;
                transferResult = session.PutFiles(fileToUpload, "/" + a.Files[2].Name + "/*.*", false, transferOptions);

                // Throw on any error
                transferResult.Check();
            }
        }
 public SessionLogReader(Session session)
     : base(session)
 {
     _position = 0;
 }
        public int removeFTPFiles(String HostName, String UserName, String Password, String remoteFilePath)
        {
            int result = 0;
            Session session = null;
            try
            {
                // Setup session options               
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Ftp,
                    HostName = HostName,
                    UserName = UserName,
                    Password = Password,
                    //HostName =  "119.59.73.48",
                    //UserName = "******",
                    //Password =  "******",
                    //  SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
                };

                using (session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);

                    // Remove files                 

                    RemovalOperationResult removalResult = null;
                    removalResult = session.RemoveFiles(remoteFilePath);

                    // Throw on any error
                    removalResult.Check();
                    // Print results
                    foreach (RemovalEventArgs removal in removalResult.Removals)
                    {
                        Console.WriteLine("Remove of {0} succeeded", removal.FileName);
                    }

                }

                result = 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                result = 1;
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
            return result;
        }
        private int Upload(String HostName, String UserName, String Password, String remotePath, String localFilePath)
        {
            int result = 0;
            Session session = null;
            try
            {
                // Setup session options               
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Ftp,
                    HostName = HostName,
                    UserName = UserName,
                    Password = Password,
                    //HostName =  "119.59.73.48",
                    //UserName = "******",
                    //Password =  "******",
                    //  SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
                };

                using (session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);



                    // upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Ascii;


                    TransferOperationResult transferResult = null;

                    transferResult = session.PutFiles(localFilePath, remotePath, false, transferOptions);


                    // Throw on any error
                    transferResult.Check();
                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    {
                        Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                    }

                }

                result = 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                result = 1;
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
            return result;
        }
Exemple #39
0
 private void DoTestConnection(object sender, DoWorkEventArgs e)
 {
     try
     {
         using (Session session = new Session())
         {
             session.Open(sessionOptions);
             session.Close();
         }
         RaiseConnectionOK();
     }
     catch (Exception ex)
     {
         RaiseConnectionFAILED();
     }
 }
Exemple #40
0
 internal SessionException(Session session, string message, Exception innerException)
     : base(message, innerException)
 {
     Session = session;
     session.Logger.WriteLine("Exception: {0}", this);
 }
        public static bool CheckForFiles()
        {
            string remoteDirectory = "/" + Properties.Settings.Default.FTPDownloadDir + "/";
            string localDirectory  = Properties.Settings.Default.RootFolderExt;
            bool   bReturn         = false;



            try
            {
                // Setup session options
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = Properties.Settings.Default.FTPAddress,
                    UserName = Properties.Settings.Default.FTPUserName,
                    Password = Properties.Settings.Default.FTPPassword,
                    SshHostKeyFingerprint = Properties.Settings.Default.SshHostKeyFingerprint
                };


                using (WinSCP.Session session = new WinSCP.Session())
                {
                    // Connect
                    session.Open(sessionOptions);

                    //List files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    RemoteDirectoryInfo files = session.ListDirectory(remoteDirectory);


                    foreach (RemoteFileInfo file in files.Files)
                    {
                        if (file.Name.ToLower().Contains(".zip"))
                        {
                            GlobalServices.SetText("frmMain", "lFTPStatus", "Checking " + file.Name);


                            if (!FileInloadStats.CheckRecordExists(file.Name))
                            {
                                long total = file.Length > 0 ? file.Length : 1;
                                int  i     = 0;
                                GlobalServices.SetText("frmMain", "lFTPStatus", "Checking " + file.Name);
                                //GlobalServices.SetProgressBar("frmMain", "pbProgress", 0, Convert.ToInt32(total), 0);
                                GlobalServices.SetText("frmMain", "lFTPStatus", "Downloading File: " + file.Name);

                                Console.WriteLine("Starting Download of file - " + file.Name + " Size - " + file.Length.ToString() + " Time - " + DateTime.Now.ToString());
                                // Download files
                                TransferOperationResult transferOperationResult = session.GetFiles(session.EscapeFileMask(remoteDirectory + file.Name), localDirectory);


                                // Check and throw if there are any errors with the transfer operation.
                                transferOperationResult.Check();

                                if (transferOperationResult.IsSuccess)
                                {
                                    var newFile = new FileInloadStats()
                                    {
                                        FileName = file.Name
                                    };
                                    FileInloadStats.InsertRecord(newFile);
                                    Console.WriteLine("Completed Download of file - " + file.Name + " Size - " + file.Length.ToString() + " Time - " + DateTime.Now.ToString());
                                }
                            }
                        }
                    }
                    bReturn = true;
                }
            }
            catch (Exception e)
            {
                bReturn = false;
                return(bReturn);
            }
            return(bReturn);
        }
        public string RunFtp(string hostIP, string port, string user, string pass, string remoteDirectory, string remoteFilePattern, string localFileDirectory, string pharmacyName, string localFileName, int numHoursGoback, string ram, ref DataTable tblExcel)
        {
            string result = "";
            string localFileDirWithDateTime;
            string filePrefix = "SFTPDownload";

            try
            {
                localFileDirWithDateTime = Helper.CreateDirectory(localFileDirectory, DateTime.Now, pharmacyName);
            }
            catch (Exception ex)
            {
                LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix,
                                     pharmacyName, "", DateTime.Now, "Failed trying to create a local Dir in " + localFileDirectory + ". Ftp for this pharm stopped.", ref tblExcel);
                return("Failure trying to create a directory in " + localFileDirectory + " for pharmacy " + pharmacyName + ". error:" + ex.Message);
            }

            try
            {//------------------------------------------------------------------------------------------------
                WinSCP.SessionOptions sessionOptions = new WinSCP.SessionOptions
                {
                    Protocol   = WinSCP.Protocol.Sftp,
                    HostName   = hostIP,
                    UserName   = user,
                    Password   = pass,
                    PortNumber = Convert.ToInt32(port)

                                 /* use these to connect to FTP, and leave out the fingerPrint.:
                                  *
                                  * _with1.Protocol = Protocol.Ftp;
                                  * _with1.FtpSecure = FtpSecure.Explicit;
                                  *
                                  */
                };
                string fingerprint = null;
                using (WinSCP.Session session = new WinSCP.Session())
                {
                    fingerprint = session.ScanFingerprint(sessionOptions);
                }
                if (fingerprint == null)
                {
                    throw new Exception("Couldnt determine Host Fingerprint");
                }
                else
                {
                    sessionOptions.SshHostKeyFingerprint = fingerprint;
                }


                using (WinSCP.Session session = new WinSCP.Session())
                {
                    sessionOptions.Timeout = TimeSpan.FromMinutes(6);  // 6 min timeout
                    //session.ExecutablePath = @"C:\Software\v11\winscp.exe";
                    session.Open(sessionOptions);

                    WinSCP.TransferOptions transferOptions = new WinSCP.TransferOptions();
                    transferOptions.TransferMode = WinSCP.TransferMode.Binary;

                    WinSCP.TransferOperationResult transferResult = default(WinSCP.TransferOperationResult);
                    transferResult = session.GetFiles(remoteDirectory + remoteFilePattern, localFileDirectory, false, transferOptions);

                    transferResult.Check();
                    //THrows the first error if not successful
                    foreach (WinSCP.TransferEventArgs transfer in transferResult.Transfers)
                    {
                        string downfileName = transfer.FileName;

                        DateTime remoteWriteTime =
                            session.GetFileInfo(downfileName).LastWriteTime;               //get the DateTime of the file.

                        if (remoteWriteTime >= DateTime.Now.AddHours(numHoursGoback * -1)) // ignore if older that the num Hours Goback spec by user
                        {
                            string localFilename = localFileDirWithDateTime + downfileName;
                            //try
                            //{

                            result += downfileName + "\r\n";
                            LogObj.WriteExcelrow("Success", enMsgType.enMsgType_Info, filePrefix,
                                                 pharmacyName, downfileName, remoteWriteTime, "", ref tblExcel);
                            // }
                            //catch (Exception ex)
                            //{
                            //    LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix,
                            //                                    pharmacyName, downfileName, remoteWriteTime, ex.Message, ref tblExcel);

                            //    return "Failure occurred trying to Download SecureFtpWinSCP file " + downfileName + " for HostIp " + hostIP + " directory " + remoteDirectory + " files " + remoteFilePattern + " error:" + ex.Message + "\r\n";
                            //}
                        }
                        else
                        {
                            result += "Should be Ignored" + downfileName + " but still nowloaded." + "\r\n";

                            LogObj.WriteExcelrow("Success", enMsgType.enMsgType_Info, filePrefix,
                                                 pharmacyName, downfileName, remoteWriteTime, " but still nowloaded.", ref tblExcel);

                            //LogObj.WriteExcelrow("Ignored", enMsgType.enMsgType_Info, filePrefix,
                            //                                    pharmacyName, downfileName, file.Attributes.LastWriteTime, "its too old", ref tblExcel);
                        }
                    }
                }
                //-------------------------------------------------------------------------------------------------------------------


                return("Successfully downloaded to local dir " + localFileDirectory + " the following files: " + result);
            }
            catch (WinSCP.SessionRemoteException ex)
            {
                LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, "Check the remote settings. " + ex.Message, ref tblExcel);
                return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n");
            }

            catch (System.TimeoutException ex)
            {
                LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, ex.Message, ref tblExcel);
                return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n");
            }


            catch (Exception ex)
            {
                LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, ex.Message, ref tblExcel);

                return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n");
            }
        }
        // --------------------------------------------------------[]
        private static void SftpUploadFiles( string localPath, string remotePath )
        {
            using( var session = new Session() ) {
                var sessionOptions = SessionOptions();
                var transferOptions = TransferOptions();

                session.Open( sessionOptions );

                var transferResult = session.PutFiles(
                    localPath,
                    remotePath,
                    false,
                    transferOptions
                    );

                transferResult.Check();
            }
        }
 public void StartSession()
 {
     this.session = (Session)this.cm.AcquireConnection(this.txn);
 }
        public DataTable Load()
        {
            StringBuilder requestUri = new StringBuilder();
            SessionOptions sessionOptions = new SessionOptions
            {
                HostName = Server,
                UserName = Username,
                Password = Password,
            };

            sessionOptions.Protocol = WinSCP.Protocol.Ftp;
            if (!String.IsNullOrEmpty(Path))
            {
                if (!Path.StartsWith("/") && !Path.StartsWith("."))
                {
                    requestUri.Append("/");
                }
                requestUri.Append(Path);
            }
            // sessionOptions.SshHostKeyFingerprint = SshHostKeyFingerprint;

            if (!String.IsNullOrEmpty(Path))
            {
                if (!Path.StartsWith("/") && !Path.StartsWith("."))
                {
                    requestUri.Append("/");
                }
                requestUri.Append(Path);
            }

            using (Session session = new Session())
            {
                if (!String.IsNullOrEmpty(WinscpPath))
                {
                    session.ExecutablePath = WinscpPath;
                }

                // prepare for output
                DataTable dataTable = new DataTable();
                dataTable.Columns.Add("Name", typeof(String));
                dataTable.Columns.Add("Size", typeof(long));
                dataTable.Columns.Add("LastModifiedDate", typeof(DateTime));
                dataTable.Columns.Add("FullPath", typeof(String));

                session.Open(sessionOptions);
                RemoteDirectoryInfo dirListing = session.ListDirectory(Path);
                Regex regex = null;
                if (!String.IsNullOrEmpty(FilterPattern))
                {
                    regex = new Regex(FilterPattern);
                }
                foreach (RemoteFileInfo fileInfo in dirListing.Files)
                {
                    if (regex == null || regex.IsMatch(fileInfo.Name))
                    {
                        dataTable.Rows.Add(new object[] { fileInfo.Name, fileInfo.Length, fileInfo.LastWriteTime, String.Format("{0}/{1}", requestUri.ToString(), fileInfo.Name) });
                    }
                }

                if (dataTable.Rows.Count > 0)
                {
                    if (!String.IsNullOrEmpty(SortOrder))
                    {
                        if (String.Compare(SortOrder, "asc", true) == 0)
                        {
                            DataView defaultView = dataTable.DefaultView;
                            defaultView.Sort = "LastModifiedDate ASC";
                            dataTable = defaultView.ToTable();
                        } if (String.Compare(SortOrder, "desc", true) == 0)
                        {
                            DataView defaultView = dataTable.DefaultView;
                            defaultView.Sort = "LastModifiedDate DESC";
                            dataTable = defaultView.ToTable();
                        }
                    }
                }
                return dataTable;
            }
        }
 public OperationResultGuard(Session session, OperationResultBase operationResult)
 {
     _session = session;
     _operationResult = operationResult;
 }
Exemple #47
0
        //单线程即可
        public static Tuple <int, string> m_fSendFile(m_cRecModel m_mRecModel, string m_sRemoteDirectory, bool m_bTest, LogTyper lt = LogTyper.LogLogger)
        {
            int    status = 0;
            string msg    = string.Empty;

            try
            {
                ///链接(S)FTP
                SessionOptions sessionOptions = new SessionOptions();
                sessionOptions.Protocol   = (Protocol)(int.Parse(m_cConfigConstants.m_sProtocol));
                sessionOptions.HostName   = m_cConfigConstants.m_sIP;
                sessionOptions.PortNumber = int.Parse(m_cConfigConstants.m_sPort);
                sessionOptions.UserName   = m_cConfigConstants.m_sUa;
                sessionOptions.FtpMode    = (FtpMode)(int.Parse(m_cConfigConstants.m_sMode));
                if (!string.IsNullOrWhiteSpace(m_cConfigConstants.m_sPwd))
                {
                    sessionOptions.Password = m_cConfigConstants.m_sPwd;
                }
                if (!string.IsNullOrWhiteSpace(m_cConfigConstants.m_sKey))
                {
                    sessionOptions.SshHostKeyFingerprint = m_cConfigConstants.m_sKey;
                }

                ///放入测试
                using (WinSCP.Session session = new WinSCP.Session())
                {
                    session.Open(sessionOptions);

                    TransferEventArgs transferEventArgs;
                    TransferOptions   transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    //是否需要创建文件夹,逐级创建
                    if (!string.IsNullOrWhiteSpace(m_sRemoteDirectory) && !session.FileExists(RemotePath.EscapeFileMask(m_sRemoteDirectory)))
                    {
                        //查找出所有目录
                        string[] m_lDirectory  = m_sRemoteDirectory.Split('/');
                        string   m_sPrefixMulu = string.Empty;

                        foreach (string m_sMulu in m_lDirectory)
                        {
                            if (!string.IsNullOrWhiteSpace(m_sMulu))
                            {
                                m_sPrefixMulu += $"/{m_sMulu}";
                                if (!session.FileExists(RemotePath.EscapeFileMask(m_sPrefixMulu)))
                                {
                                    session.CreateDirectory(RemotePath.EscapeFileMask(m_sPrefixMulu));

                                    Log.Instance.Debug($"逐级创建(S)FTP目录:“{m_sPrefixMulu}”", lt);
                                }
                            }
                        }
                    }

                    //判断文件是否已经上传
                    if (!session.FileExists(RemotePath.EscapeFileMask($"{m_sRemoteDirectory}/{System.IO.Path.GetFileName(m_mRecModel.mimiFile)}")))
                    {
                        //如果为测试,文件不进行删除
                        transferEventArgs = session.PutFileToDirectory(m_mRecModel.mimiFile, RemotePath.EscapeFileMask(m_sRemoteDirectory), !m_bTest, transferOptions);

                        string m_sErrMsg = string.Join(",", transferEventArgs?.Error?.Message);
                        if (!string.IsNullOrWhiteSpace(m_sErrMsg))
                        {
                            Log.Instance.Debug(m_sErrMsg, lt);
                            status = 1;
                            msg    = m_sErrMsg;
                        }
                        else
                        {
                            status = 0;
                            msg    = "录音上传(S)FTP成功";
                        }
                    }
                    else
                    {
                        status = 0;
                        msg    = "录音已存在,略过上传(S)FTP";

                        if (!m_bTest)
                        {
                            Log.Instance.Debug($"{m_mRecModel.Id}:“{msg}”", lt);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                status = 1;
                msg    = ex.Message;

                //如果有误
                if (!m_bTest)
                {
                    m_cSQL.m_fSetActionState(m_mRecModel.Id, "3", $"上传(S)FTP错误:{msg}", lt);
                }

                //打印一下错误,处理一下此处导致计划任务无法继续的问题
                Log.Instance.Debug(ex, lt);
            }
            return(new Tuple <int, string>(status, msg));
        }