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());
                }
            }
        }
Exemple #3
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(); 
            } 
        } 
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
        public List<String> GetHeaders(string winSCPPath, string csvDirectory, string csvFile, string rslReport,
                                       string parameters, string windowsOutputPath)
        {
            List<String> headerList = null;
            String reportHeaderFileName = rslReport + "-headers.txt";

            using (Session session = new Session())
            {
                try
                {
                    session.ExecutablePath = winSCPPath;
                    session.Open(winSCPSessionOptions);
                }
                catch (Exception e)
                {
                    throw new Exception("Could not open a WinSCP session!\n\n" + e.Message);
                }

                try
                {
                    DirectoryInfo dir = new DirectoryInfo(windowsOutputPath);
                    if (!dir.Exists) { dir.Create(); }
                }
                catch (Exception e)
                {
                    throw new Exception(String.Format("Could not create the following directory: {0}\n\n{1}",
                                        windowsOutputPath, e.Message));
                }

                String newCsvFileName = rslReport + ".csv";

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

                try
                {
                    transferResult = session.GetFiles(csvDirectory + csvFile, windowsOutputPath + newCsvFileName, false, transferOptions);
                    transferResult.Check();
                }
                catch (Exception e)
                {
                    throw new Exception(String.Format("Could not transfer the file \"{0}\" in Unix server to the Windows output as {1}\n\n{2}",
                                        csvDirectory + csvFile, windowsOutputPath + newCsvFileName, e.Message));
                }

                try
                {
                    session.ExecuteCommand("rm -f " + csvDirectory + csvFile);
                }
                catch (Exception e)
                {
                    throw new Exception(String.Format("Could not execute de command: rm {0}\n\n{1}",
                                        csvDirectory + csvFile, e.Message));
                }

                if (File.Exists(windowsOutputPath + newCsvFileName))
                {
                    headerList = new List<string>();
                    string line;

                    try
                    {
                        using (var reader = File.OpenText(windowsOutputPath + newCsvFileName))
                        {
                            line = reader.ReadLine();
                            if (line != null)
                            {
                                line = line.Replace("\"", "");
                                headerList = line.Split(',').ToList();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not open file: {0}\n\n{1}", windowsOutputPath + newCsvFileName, e.Message));
                    }

                    try
                    {
                        File.Delete(windowsOutputPath + newCsvFileName);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not delete the following file: {0}\n\n{1}",
                                        windowsOutputPath + newCsvFileName, e.Message));
                    }
                }

                using (var sw = new StreamWriter(windowsOutputPath + reportHeaderFileName))
                {
                    foreach (string s in headerList) { sw.WriteLine(s); }
                }
            }

            return headerList;
        }
Exemple #6
1
        public List<String> GetRSLList(string winSCPPath, string rslFilePath, string windowsOutput)
        {
            List<String> rslList = null;
            String windowsOutputPath = windowsOutput + @"GFT_DiffTool_Output\";

            if (File.Exists(windowsOutputPath + "rsls.txt"))
            {
                rslList = new List<string>();
                string line;

                try
                {
                    using (var reader = File.OpenText(windowsOutputPath + "rsls.txt"))
                    {
                        rslList = new List<String>();
                        while ((line = reader.ReadLine()) != null)
                        {
                            rslList.Add(line);
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new Exception(String.Format("Could not open file: {0}\n\n{1}", windowsOutputPath + "rsls.txt", e.Message));
                }
            }
            else
            {
                using (Session session = new Session())
                {
                    try
                    {
                        session.ExecutablePath = winSCPPath;
                        session.Open(winSCPSessionOptions);
                    }
                    catch (Exception e)
                    {
                        throw new Exception("Could not open a WinSCP session!\n\n" + e.Message);
                    }

                    try
                    {
                        DirectoryInfo dir = new DirectoryInfo(windowsOutputPath);
                        if (!dir.Exists) { dir.Create(); }
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not create the following directory: {0}\n\n{1}",
                                            windowsOutputPath, e.Message));
                    }

                    string rslFile = rslFilePath.Split('/')[rslFilePath.Split('/').Length - 1];

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

                    try
                    {
                        transferResult = session.GetFiles(rslFilePath, windowsOutputPath + rslFile, false, transferOptions);
                        transferResult.Check();
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not transfer the file \"{0}\" in Unix server to the Windows output as {1}\n\n{2}",
                                            rslFilePath, windowsOutputPath + rslFile, e.Message));
                    }

                    try
                    {
                        if (File.Exists(windowsOutputPath + "rsls.txt")) { File.Delete(windowsOutputPath + "rsls.txt"); }
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not delete the following file: {0}\n\n{1}",
                                            windowsOutputPath + "rsls.txt", e.Message));
                    }

                    try
                    {
                        string line;
                        using (var reader = File.OpenText(windowsOutputPath + rslFile))
                        using (var sw = new StreamWriter(windowsOutputPath + "rsls.txt"))
                        {
                            rslList = new List<String>();
                            while ((line = reader.ReadLine()) != null)
                            {
                                line = line.Trim();
                                if (!String.IsNullOrEmpty(line) && !line.StartsWith("//"))
                                {
                                    String rsl = line.Split(' ')[0].Split('\t')[0];
                                    if (rsl.EndsWith(".rsl"))
                                    {
                                        rslList.Add(rsl);
                                        sw.WriteLine(rsl);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not create the following file: {0}\n\n{1}",
                                            windowsOutputPath + "rsls.txt", e.Message));
                    }

                    try
                    {
                        File.Delete(windowsOutputPath + rslFile);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not delete the following file: {0}\n\n{1}",
                                            windowsOutputPath + rslFile, e.Message));
                    }
                }
            }

            return rslList;
        }
Exemple #7
0
 public bool Get(string remotePath, string localDir)
 {
     try
     {
         var result = _session.GetFiles(remotePath, localDir, false);
         return(result.IsSuccess);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Exemple #8
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 #9
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 #10
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);
                }
            }
        }
        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);
        }
        // --------------------------------------------------------[]
        private static void _DownloadFiles( string remotePath, string localPath )
        {
            using( var session = new Session() ) {
                var sessionOptions = SessionOptions();
                var transferOptions = TransferOptions();

                session.Open( sessionOptions );

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

                transferResult.Check();
            }
        }
Exemple #13
0
        private static void DownLoadFile(Session session, TransferOptions transferOptions, String remotefile, string localfolder)
        {
            TransferOperationResult transferResult;
            transferResult = session.GetFiles(remotefile, localfolder, false, transferOptions);

            transferResult.Check();

            foreach (TransferEventArgs transfer in transferResult.Transfers)
            {
                Console.WriteLine("Download of {0} succeeded", transfer.FileName);
            }
        }
Exemple #14
0
        public void DownloadCSV(string winSCPPath, string csvDirectory, string serverType, string version,
                                string csvFile, string report, string portfolio, string windowsOutput)
        {
            using (Session session = new Session())
            {
                try
                {
                    // Connect
                    session.ExecutablePath = winSCPPath;
                    session.Open(winSCPSessionOptions);
                }
                catch (Exception e)
                {
                    throw new Exception("Could not open a WinSCP session!\n\n" + e.Message);
                }

                String rslReport = Path.GetFileNameWithoutExtension(report);
                String windowsOutputPath = windowsOutput + @"GFT_DiffTool_Output\"
                    + DateTime.Today.ToString("yyyy-MM-dd") + "-" + version + @"\" + serverType + @"\";

                try
                {
                    DirectoryInfo dir = new DirectoryInfo(windowsOutputPath);
                    if (!dir.Exists) { dir.Create(); }
                }
                catch (Exception e)
                {
                    throw new Exception(String.Format("Could not create the following directory: {0}\n\n{1}",
                                        windowsOutputPath, e.Message));
                }

                portfolio = portfolio.Replace(' ', '_');
                String newCsvFileName = serverType + "." + portfolio + "." + rslReport + "." + version + ".csv";

                #region Clean Directory

                if (File.Exists(windowsOutputPath + newCsvFileName))
                {
                    try
                    {
                        File.Delete(windowsOutputPath + newCsvFileName);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not delete the following file: {0}\n\n{1}",
                                        windowsOutputPath + newCsvFileName, e.Message));
                    }
                }

                if (File.Exists(windowsOutputPath + "temp_" + newCsvFileName))
                {
                    try
                    {
                        File.Delete(windowsOutputPath + "temp_" + newCsvFileName);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not delete the following file: {0}\n\n{21}",
                                        windowsOutputPath + "temp_" + newCsvFileName, e.Message));
                    }
                }

                if (File.Exists(windowsOutputPath + "backup_" + newCsvFileName))
                {
                    try
                    {
                        File.Delete(windowsOutputPath + "backup_" + newCsvFileName);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not delete the following file: {0}\n\n{1}",
                                        windowsOutputPath + "backup_" + newCsvFileName, e.Message));
                    }
                }

                if (File.Exists(windowsOutputPath + "ERRORS_" + newCsvFileName))
                {
                    try
                    {
                        File.Delete(windowsOutputPath + "ERRORS_" + newCsvFileName);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not delete the following file: {0}\n\n{21}",
                                        windowsOutputPath + "ERRORS_" + newCsvFileName, e.Message));
                    }
                }

                #endregion

                #region Transfer File

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

                try
                {
                    transferResult = session.GetFiles(csvDirectory + csvFile, windowsOutputPath + newCsvFileName, false, transferOptions);
                    transferResult.Check();
                }
                catch (Exception e)
                {
                    throw new Exception(String.Format("Could not transfer the file \"{0}\" in Unix server to the Windows output as {1}\n\n{2}",
                                        csvDirectory + csvFile, windowsOutputPath + newCsvFileName, e.Message));
                }

                try
                {
                    session.ExecuteCommand("rm -f " + csvDirectory + csvFile);
                }
                catch (Exception e)
                {
                    throw new Exception(String.Format("Could not execute de command: rm {0}\n\n{1}",
                                        csvDirectory + csvFile, e.Message));
                }

                #endregion

                if (File.Exists(windowsOutputPath + newCsvFileName))
                {
                    string header;
                    string line = "";
                    int errorCount = 0;
                    try
                    {
                        using (var reader = File.OpenText(windowsOutputPath + newCsvFileName))
                        using (var writer = File.CreateText(windowsOutputPath + "temp_" + newCsvFileName))
                        using (var errorWriter = File.CreateText(windowsOutputPath + "ERRORS_" + newCsvFileName))
                        {
                            header = reader.ReadLine();
                            writer.WriteLine(header);
                            errorWriter.WriteLine("\"Error #\",\"Description\"");
                            while (line != null && (line = reader.ReadLine()) != null)
                            {
                                if (line.Contains("\"Error #\""))
                                {
                                    errorCount++;
                                    while ((line = reader.ReadLine()) != null && !header.Equals(line))
                                    {
                                        errorWriter.WriteLine(line);
                                    }
                                }
                                else
                                {
                                    if (!header.Equals(line) && !line.Trim().Equals("") && line.StartsWith("\""))
                                    {
                                        writer.WriteLine(line);
                                    }
                                }
                            }
                        }
                        File.Replace(windowsOutputPath + "temp_" + newCsvFileName,
                                        windowsOutputPath + newCsvFileName,
                                        windowsOutputPath + "backup_" + newCsvFileName);

                        if (File.Exists(windowsOutputPath + "backup_" + newCsvFileName))
                        {
                            File.Delete(windowsOutputPath + "backup_" + newCsvFileName);
                        }
                        if (File.Exists(windowsOutputPath + "ERRORS_" + newCsvFileName) && errorCount == 0)
                        {
                            File.Delete(windowsOutputPath + "ERRORS_" + newCsvFileName);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("Could not open the file: {0}\n\n{1}", newCsvFileName, e.Message));
                    }
                }
            }
        }
        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");
            }
        }
Exemple #16
-1
        public static void SyncFile()
        {
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = Param.SqlCeConfig["sshServer"].ToString(),
                UserName = Param.SqlCeConfig["sshUsername"].ToString(),
                SshPrivateKeyPath = Param.SqlCeConfig["sshKeyPath"].ToString(),
                PortNumber = int.Parse(Param.SqlCeConfig["sshPort"].ToString()),
                SshHostKeyFingerprint = Param.SqlCeConfig["sshHostKey"].ToString()
            };

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

                    RemoteFileInfo fileInfo = session.GetFileInfo(Param.ScpSoftwarePath + "/Updater.exe");
                    FileInfo fi = new FileInfo("Updater.exe");
                    if (DateTimeToUnixTimestamp(fi.LastWriteTime) != DateTimeToUnixTimestamp(fileInfo.LastWriteTime))
                    {
                        try
                        {
                            TransferOptions transferOptions = new TransferOptions();
                            transferOptions.TransferMode = TransferMode.Automatic;
                            TransferOperationResult transferResult;
                            transferResult = session.GetFiles(Param.ScpSoftwarePath + "/Updater.exe", "Updater.exe", false, transferOptions);
                            transferResult.Check();
                            foreach (TransferEventArgs transfer in transferResult.Transfers)
                            {
                                WriteLog(string.Format("Download of {0} : {1} succeeded", transfer.FileName, transfer.Destination));
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteErrorLog(string.Format("SCP Download Error : {0}", ex.Message));
                        }
                    }

                    //session.FileTransferred += FileTransferred;
                    if (Directory.Exists(Param.ApplicationDataPath + @"\log"))
                    {
                        try
                        {
                            TransferOptions transferOptions = new TransferOptions();
                            transferOptions.TransferMode = TransferMode.Automatic;

                            SynchronizationResult synchronizationResult;
                            synchronizationResult = session.SynchronizeDirectories(SynchronizationMode.Remote,
                                Param.ApplicationDataPath + @"\log", Param.ScpLogPath, false, false, SynchronizationCriteria.Time, transferOptions);
                            synchronizationResult.Check();
                        }
                        catch (Exception ex)
                        {
                            WriteErrorLog(string.Format("SCP SynchronizeDirectories Error : {0}", ex.Message));
                        }
                    }

                    session.Close();
                }
            }

        }