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);
            }
        }
Example #2
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;
            }
        }
Example #3
0
        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;
        }
 // --------------------------------------------------------[]
 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();
 }
Example #5
0
 public ArrayList GetFileList(string fTP_ORDER_PATH, string fileType)
 {
     try
     {
         var       list    = _session.ListDirectory(fTP_ORDER_PATH);
         ArrayList objList = new ArrayList();
         foreach (var fileInfo in list.Files.ToList())
         {
             if (Path.GetExtension(fileInfo.Name) == fileType)
             {
                 objList.Add(fileInfo.Name);
             }
         }
         return(objList);
     }
     catch
     {
         return(null);
     }
 }
Example #6
0
        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 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();
            }
        }
Example #8
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.");
         }
     }
 }
Example #9
0
        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;
            }
        }
Example #10
0
        private static List<FileObject> ListFiles(Session session, String remotefolder)
        {
            RemoteDirectoryInfo dirinfo = session.ListDirectory(remotefolder);

            List<FileObject> filelist = new List<FileObject>();

            foreach (RemoteFileInfo fileInfo in dirinfo.Files)
            {
                if (fileInfo.Name.Equals(".") || fileInfo.Name.Equals("..")) { continue; }
                if (Params.Filter.Length > 2 && fileInfo.Name.Contains(Params.Filter))
                {
                    filelist.Add(new FileObject(fileInfo.Name, fileInfo.Length, fileInfo.LastWriteTime));
                }

                //Console.WriteLine("{0} with size {1}, permissions {2} and last modification at {3}",
                //    fileInfo.Name, fileInfo.Length, fileInfo.FilePermissions, fileInfo.LastWriteTime);
            }

            return filelist;
        }
Example #11
0
        public static int Main(string[] args)
        {
            //connectToDb();
            Console.WriteLine("Let's reorganize some files!");

            try
            {
                // Setup session
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = ConfigurationManager.AppSettings["hostName"],
                    UserName = ConfigurationManager.AppSettings["userName"],
                    Password = ConfigurationManager.AppSettings["password"],
                    SshHostKeyFingerprint = ConfigurationManager.AppSettings["sshHostKeyFingerprint"]
                };

                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);
                    Console.WriteLine("Connected to session.");
                    // TODO: make source path editable
                    String path = "/home/cetus/shared/HARP Deployment and Recovery Files";
                    Console.WriteLine("Source path is {0}", path);
                    RemoteDirectoryInfo directory = session.ListDirectory(path);
                    List<RemoteFileInfo> sourceFiles = new List<RemoteFileInfo>(); // to hold file names that will be sorted
                    foreach (RemoteFileInfo fileInfo in directory.Files)
                    {
                        if (!(Regex.IsMatch(fileInfo.Name, @"^\.")) && !(Regex.IsMatch(fileInfo.Name, @"^\d")) && fileInfo.IsDirectory)
                        {
                            sourceFiles.Add(fileInfo);
                        }
                    }
                    Console.WriteLine("Files found, processing and sorting.");

                    // Sort files alphabetically
                    sourceFiles.Sort(delegate (RemoteFileInfo x, RemoteFileInfo y)
                    {
                        if (x.Name == null && y.Name == null) return 0;
                        else if (x.Name == null) return -1;
                        else if (y.Name == null) return 1;
                        else return y.Name.CompareTo(x.Name);
                    });

                    // Destination path of where the directories holding the targets willbe temporarily held until transferred back to session
                    String destPath = "C:/Users/Harp/Desktop/temp";
                    // TODO: make destination path editable
                    Console.WriteLine("Destination path is {0}", destPath);
                    FileTransferManager fileTransfer = new FileTransferManager(path, destPath, session);
                    Boolean doneTargets = false;
                    while (!doneTargets)
                    {
                        Console.WriteLine("Create new target? (Y/N)");
                        String response = Console.ReadLine();
                        switch (response)
                        {
                            case "Y":
                                fileTransfer.createNewTarget();
                                break;
                            case "N":
                                doneTargets = true;
                                break;
                            default:
                                break;
                        }
                    }
                    Boolean done = false;
                    int i = 0;
                    while (!done)
                    {
                        Console.WriteLine("[E]xit [Y]es [Any key to continue]");
                        RemoteFileInfo aSourceFile = sourceFiles[i];
                        Console.WriteLine("Would you like to organize {0}(Y/N)?", aSourceFile.Name);
                        String answer = Console.ReadLine();
                        switch (answer)
                        {
                            case "Y":
                                fileTransfer.setCurrentTransferSrc(aSourceFile); // set the path to the current source 
                                fileTransfer.checkDestinationDir();              // set path to destination of transfer
                                fileTransfer.setTargetSrcPaths();                // set the paths of the targets
                                fileTransfer.configureTargetRules();             // configure target rules
                                fileTransfer.transferTargets();                  // transfer the target files
                                break;
                            case "N":
                                break;
                            case "E":
                                done = true;
                                break;
                            default:
                                continue;
                        }
                        i++;
                    }
                    return 0;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error: {0}", e);
                return 1;
            }
        }
Example #12
0
        private void UploadFile(string fileToUpload)
        {
            lbLogs.Items.Add("File to upload: " + fileToUpload);

              bpLoadFile.Value = 0;
              bpLoadFile.DisplayStyle = ProgressBarDisplayText.Percentage;

              SessionOptions sessionOptions = new SessionOptions
              {
            Protocol = Protocol.Ftp,
            HostName = this.cloudFoldersInfo.data.host,
            UserName = this.cloudFoldersInfo.data.user,
            Password = this.cloudFoldersInfo.data.password,
              };

              using (Session session = new Session())
              {
            // Will continuously report progress of transfer
            session.FileTransferProgress += SessionFileTransferProgress;
            // Connect
            session.Open(sessionOptions);
            // Upload files
            TransferOptions transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;

            var a = session.ListDirectory("/");
            this.remoteUserFolderName = a.Files[2].Name;
            var filePath = "/" + this.remoteUserFolderName + "/" + filename;
            if (!session.FileExists(filePath))
            {
              TransferOperationResult transferResult;
              transferResult = session.PutFiles(fileToUpload, "/" + this.remoteUserFolderName + "/*.*", false, transferOptions);
              transferResult.Check();
              if (transferResult.IsSuccess)
              {
            bpLoadFile.CustomText = "Succeed!";
              }
              else
              {
            bpLoadFile.CustomText = "Failed!";
              }
            }
            else
            {
              bpLoadFile.CustomText = "Succeed!";
              bpLoadFile.Update();
            }
            lbLogs.Items.Add("Package has been uploaded!");
            bpLoadFile.DisplayStyle = ProgressBarDisplayText.CustomText;
              }
        }