Ejemplo n.º 1
0
        private static void DownloadDirectory(FtpConnection ftp, string p, string p_2)
        {
            string targetFolder = Path.GetFullPath(p_2);
            //string sourceFolder = ftp.GetCurrentDirectory() + '/' + p;

            DirectoryInfo localDir = new DirectoryInfo(targetFolder);

            if (localDir.Exists)
            {
                localDir.Delete(true);
            }

            localDir.Create();

            ftp.SetCurrentDirectory(p);
            ftp.SetLocalDirectory(localDir.FullName);
            foreach (var file in ftp.GetFiles())
            {
                string localFilename = localDir.FullName + Path.DirectorySeparatorChar + file.Name;
                if (File.Exists(localFilename))
                {
                    File.Delete(localFilename);
                }

                ftp.GetFile(file.Name, false);
            }

            foreach (var directory in ftp.GetDirectories())
            {
                Directory.CreateDirectory(directory.Name);
                DownloadDirectory(ftp, directory.Name, targetFolder + Path.DirectorySeparatorChar + directory.Name);
            }

            ftp.SetCurrentDirectory("..");
        }
Ejemplo n.º 2
0
        private void DownloadDirectories(FtpConnection ftp, FtpDirectoryInfo[] dic, string remotePath, string localPath)
        {
            foreach (var ftpDirectoryInfo in dic.Where(d => d.Name != "." && d.Name != ".."))
            {
                if (_activeConnections < MaxActiveConnections)
                {
                    _activeConnections++;

                    _downloadTasks.Add(Task.Run(() =>
                    {
                        using (FtpConnection ftp2 = GetNewConnection())
                        {
                            ftp2.Open();
                            ftp2.Login();

                            ftp2.SetCurrentDirectory(remotePath + "/" + ftpDirectoryInfo.Name);

                            DownloadFiles(ftp2, ftp2.GetFiles(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name));
                            DownloadDirectories(ftp2, ftp2.GetDirectories(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name));
                        }
                    }));
                }
                else
                {
                    ftp.SetCurrentDirectory(remotePath + "/" + ftpDirectoryInfo.Name);
                    DownloadFiles(ftp, ftp.GetFiles(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name));
                    DownloadDirectories(ftp, ftp.GetDirectories(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name));
                }
            }
        }
Ejemplo n.º 3
0
        private void BtnGetDirectoriesClick(object sender, EventArgs e)
        {
            FtpDirectoryInfo[] ftpDirectoryInfos = _ftp.GetDirectories();

            lbDirectories.Items.Clear();
            lbDirectories.Items.AddRange(ftpDirectoryInfos.OrderBy(di => di.Name).Select(di => (object)di.Name).ToArray());
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 获取目录下的directory 和files
        /// </summary>
        /// <returns></returns>
        public String[] getAllFiles()
        {
            StringBuilder result = new StringBuilder();

            try
            {
                foreach (var dir in conn.GetDirectories(conn.GetCurrentDirectory()))
                {
                    result
                    .Append(dir.Attributes.ToString()).Append("?")
                    .Append(dir.Name).Append("?")
                    .Append("0").Append("?")
                    .Append(dir.LastWriteTime).Append("?")
                    .Append("\n");
                }
                foreach (var f in conn.GetFiles(conn.GetCurrentDirectory()))
                {
                    result
                    .Append(f.Attributes).Append("?")
                    .Append(f.Name).Append("?")
                    .Append(conn.GetFileSize(conn.GetCurrentDirectory() + "/" + f.Name)).Append("?")
                    .Append(f.LastWriteTime).Append("?")
                    .Append("\n");
                }
            }
            catch
            {
                MessageBox.Show("ftp has lost connection!", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(result.ToString().Split('\n'));
        }
Ejemplo n.º 5
0
        public static FtpDirectoryInfo[] GetDirectories(string path)
        {
            FtpConnection conn = GetFtpConnection();

            conn.Open();
            conn.Login();
            FtpDirectoryInfo[] exists = conn.GetDirectories(path);
            conn.Close();
            conn.Dispose();
            return(exists);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// 获取设定目录下所有的文件夹列表(仅文件夹)
 /// </summary>
 /// <param name="LocaPath">设定路径</param>
 public virtual string[] GetDirectoryList(string LocaPath)
 {
     try
     {
         var directories = ftpConnection.GetDirectories(LocaPath);
         var strs        = new List <string>();
         directories.ToList().ForEach(u => {
             if (u.Name != "." && u.Name != "..")
             {
                 strs.Add(u.Name);
             }
         });
         return(strs.ToArray());
     }
     catch
     {
         throw;
     }
 }
Ejemplo n.º 7
0
        public static void getFile(ref string UserName, ref string PassWord, ref string ServerName, ref string FileName)
        {
            using (FtpConnection ftp = new FtpConnection("ServerName", "UserName", "PassWord"))
            {
                ftp.Open();                                   /* Open the FTP connection */
                ftp.Login();                                  /* Login using previously provided credentials */

                if (ftp.DirectoryExists("/incoming"))         /* check that a directory exists */
                {
                    ftp.SetCurrentDirectory("/incoming");     /* change current directory */
                }
                if (ftp.FileExists("/incoming/file.txt"))     /* check that a file exists */
                {
                    ftp.GetFile("/incoming/file.txt", false); /* download /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */
                }
                //do some processing

                try
                {
                    ftp.SetCurrentDirectory("/outgoing");
                    ftp.PutFile(@"c:\localfile.txt", "file.txt"); /* upload c:\localfile.txt to the current ftp directory as file.txt */
                }
                catch (FtpException e)
                {
                    Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message));
                }

                foreach (var dir in ftp.GetDirectories("/incoming/processed"))
                {
                    Console.WriteLine(dir.Name);
                    Console.WriteLine(dir.CreationTime);
                    foreach (var file in dir.GetFiles())
                    {
                        Console.WriteLine(file.Name);
                        Console.WriteLine(file.LastAccessTime);
                    }
                }
            }
        } // End getFile()
Ejemplo n.º 8
0
        public void ClearFtp(FtpConnection ftp, string directory)
        {
            ftp.SetCurrentDirectory(directory);
            var dirs = ftp.GetDirectories();

            foreach (var dir in dirs)
            {
                if ((dir.Name != ".") && (dir.Name != ".."))
                {
                    ClearFtp(ftp, dir.Name); //Recursive call
                    ftp.RemoveDirectory(dir.Name);
                }
            }

            foreach (var file in ftp.GetFiles())
            {
                ftp.RemoveFile(file.Name);
            }

            if (ftp.GetCurrentDirectory() != "/")
            {
                ftp.SetCurrentDirectory("..");
            }
        }
Ejemplo n.º 9
0
        public void PublishToGitFTP(DeploymentModel model)
        {
            if (model.GitDeployment)
            {
                Logger.Debug("Executing git add");

                var addProcess          = new Process();
                var addProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" add -A"
                };
                addProcess.StartInfo           = addProcessStartInfo;
                addProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                addProcess.ErrorDataReceived  += (sender, args) => Logger.Debug(args.Data);
                addProcess.Start();
                addProcess.BeginOutputReadLine();
                addProcess.BeginErrorReadLine();
                addProcess.WaitForExit();

                Logger.Debug("git add process to exited");

                Logger.Debug("Executing git email config process");

                var emailProcess          = new Process();
                var emailProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.email \"[email protected]\""
                };
                emailProcess.StartInfo           = emailProcessStartInfo;
                emailProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                emailProcess.ErrorDataReceived  += (sender, args) => Logger.Debug(args.Data);
                emailProcess.Start();
                emailProcess.BeginOutputReadLine();
                emailProcess.BeginErrorReadLine();
                emailProcess.WaitForExit();
                Logger.Debug("git email config process to exited");

                Logger.Debug("Executing git name config process");

                var userProcess          = new Process();
                var userProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.name \"barbato\""
                };
                userProcess.StartInfo           = userProcessStartInfo;
                userProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                userProcess.ErrorDataReceived  += (sender, args) => Logger.Debug(args.Data);
                userProcess.Start();
                userProcess.BeginOutputReadLine();
                userProcess.BeginErrorReadLine();
                userProcess.WaitForExit();

                Logger.Debug("git name config process to exited");

                Logger.Debug("Executing git commit");

                var commitProcess          = new Process();
                var commitProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath +
                                "\" commit -a -m \"Static Content Regenerated\""
                };
                commitProcess.StartInfo           = commitProcessStartInfo;
                commitProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                commitProcess.ErrorDataReceived  += (sender, args) => Logger.Debug(args.Data);
                commitProcess.Start();
                commitProcess.BeginOutputReadLine();
                commitProcess.BeginErrorReadLine();
                commitProcess.WaitForExit();

                Logger.Debug("git commit process to exited");

                Logger.Debug("Executing git push");

                var pushProcess          = new Process();
                var pushProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" push -f origin master"
                };
                pushProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                pushProcess.ErrorDataReceived  += (sender, args) => Logger.Debug(args.Data);
                pushProcess.StartInfo           = pushProcessStartInfo;
                pushProcess.Start();
                pushProcess.BeginOutputReadLine();
                pushProcess.BeginErrorReadLine();
                pushProcess.WaitForExit();

                Logger.Debug("git push process to exited");
            }
            else
            {
                using (ftp = new FtpConnection(model.FTPServer, model.FTPUsername, model.FTPPassword))
                {
                    try
                    {
                        ftp.Open();
                        ftp.Login();

                        if (!string.IsNullOrWhiteSpace(model.FTPPath))
                        {
                            var parrentDirectory = String.Format("/{0}", Path.GetDirectoryName(model.FTPPath).Replace(Path.DirectorySeparatorChar, '/'));
                            /* Get name of the directory */
                            var checkingDirectory = String.Format("{0}", Path.GetFileName(model.FTPPath)).ToLower();
                            /* Get all child directories info of the parent directory */
                            var ftpDirectories = ftp.GetDirectories(parrentDirectory);
                            /* check if the given directory exists in the returned result */
                            var exists = ftpDirectories.Any(d => d.Name.ToLower() == checkingDirectory);

                            if (!exists)
                            {
                                ftp.CreateDirectory(model.FTPPath);
                            }

                            ftp.SetCurrentDirectory(model.FTPPath);
                        }

                        FtpBlogFiles(publishGitPath, model.FTPPath);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
Ejemplo n.º 10
0
        void connectEvent(object sender, System.EventArgs e)
        {
            try
            {
                bool isFinished = false;
                if (new Regex(ipFormat).IsMatch(ipBox.Text))
                {
                    ftp = new FtpConnection(ipBox.Text);
                    NewThread(new System.Action(() =>
                    {
                        for (int i = defaultSize; i < maxSize; i++)
                        {
                            this.Size = new System.Drawing.Size(389, i);
                        }
                        ftp.SetCurrentDirectory("/dev_hdd0/home");

                        foreach (var item in ftp.GetDirectories("/dev_hdd0/home"))
                        {
                            if (item.Name.Length > 5)
                            {
                                accLists.Items.Add(ftp.ReadFile("/dev_hdd0/home/" + item.Name + "/localusername"));
                                allusers.Add(item.Name);
                            }
                        }
                        isFinished = true;
                    }));
                    while (!isFinished)
                    {
                        Application.DoEvents();
                    }
                    this.commentBox.Depth                    = 0;
                    this.commentBox.Hint                     = "";
                    this.commentBox.Location                 = new System.Drawing.Point(24, 267);
                    this.commentBox.MouseState               = MaterialSkin.MouseState.HOVER;
                    this.commentBox.Name                     = "materialSingleLineTextField1";
                    this.commentBox.PasswordChar             = '\0';
                    this.commentBox.SelectedText             = "";
                    this.commentBox.SelectionLength          = 0;
                    this.commentBox.SelectionStart           = 0;
                    this.commentBox.Size                     = new System.Drawing.Size(339, 23);
                    this.commentBox.TabIndex                 = 3;
                    this.commentBox.UseSystemPasswordChar    = false;
                    this.sendComment.AutoSize                = true;
                    this.sendComment.AutoSizeMode            = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
                    this.sendComment.Depth                   = 0;
                    this.sendComment.Location                = new System.Drawing.Point(134, 303);
                    this.sendComment.Margin                  = new System.Windows.Forms.Padding(4, 6, 4, 6);
                    this.sendComment.MouseState              = MaterialSkin.MouseState.HOVER;
                    this.sendComment.Name                    = "sendComment";
                    this.sendComment.Primary                 = false;
                    this.sendComment.Size                    = new System.Drawing.Size(118, 36);
                    this.sendComment.TabIndex                = 4;
                    this.sendComment.Text                    = "Send Comment";
                    this.sendComment.UseVisualStyleBackColor = true;
                    this.sendComment.Click                  += sendCommentClick;
                    this.Controls.Add(this.commentBox);
                    this.Controls.Add(this.sendComment);
                }
                else
                {
                    MetroMessageBox.Show(this, "Error ip addrees not in correct format", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MetroMessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 11
0
        public async Task <bool> Backup(string targetFolder)
        {
            try
            {
                ConsoleService.WriteToConsole("started FTP Service");
                if (Directory.Exists(targetFolder))
                {
                    Directory.Delete(targetFolder, true);
                }

                Directory.CreateDirectory(targetFolder);

                try
                {
                    try
                    {
                        using (FtpConnection ftp = GetNewConnection())
                        {
                            ftp.Open();                                           /* Open the FTP connection */
                            ftp.Login();                                          /* Login using previously provided credentials */

                            ftp.SetCurrentDirectory(ConfiguredKeyValues[Folder]); /* change current directory */

                            DownloadDirectories(ftp, ftp.GetDirectories(), ConfiguredKeyValues[Folder], targetFolder);

                            Task.WaitAll(_downloadTasks.ToArray());
                            _downloadTasks.Clear();
                            _activeConnections = 0;
                        }
                    }
                    catch (FtpException e)
                    {
                        ConsoleService.WriteToConsole($"FTP Error: {e.ErrorCode} {e.Message}");
                        DoLog("FTP failed: " + ConfiguredKeyValues[Folder] + " (exception occured)");
                        return(false);
                    }

                    ConsoleService.WriteToConsole("Zipping file contents");

                    var tempFileName = Guid.NewGuid().ToString();
                    try
                    {
                        using (ZipFile zip = new ZipFile())
                        {
                            zip.AddProgress  += ZipOnAddProgress;
                            zip.SaveProgress += ZipOnSaveProgress;
                            zip.AddDirectory(targetFolder);
                            ConsoleService.WriteToConsole("");
                            zip.CompressionLevel = CompressionLevel.BestCompression;
                            zip.Save(Path.Combine(targetFolder, tempFileName));
                            ConsoleService.WriteToConsole("");
                        }
                    }
                    catch (Exception ex)
                    {
                        ConsoleService.WriteToConsole("Exception occurred: " + ex);
                        DoLog("failed: " + ConfiguredKeyValues[Folder] + " (exception occured)");
                        return(false);
                    }

                    ConsoleService.WriteToConsole("Cleaning up...");
                    try
                    {
                        var dics = Directory.GetDirectories(targetFolder);
                        foreach (var dic in dics)
                        {
                            Directory.Delete(dic, true);
                        }

                        foreach (var file in Directory.GetFiles(targetFolder))
                        {
                            if (!file.EndsWith(tempFileName))
                            {
                                File.Delete(file);
                            }
                        }

                        File.Move(Path.Combine(targetFolder, tempFileName), Path.Combine(targetFolder, "archive.zip"));
                    }
                    catch (Exception ex)
                    {
                        ConsoleService.WriteToConsole("Exception occurred: " + ex);
                        DoLog("failed: " + ConfiguredKeyValues[Folder] + " (exception occured)");
                        return(false);
                    }
                    return(true);
                }
                catch (Exception ex)
                {
                    ConsoleService.WriteToConsole("exception occured with folder " + ConfiguredKeyValues[Folder] + ": " + ex);
                    DoLog("failed: " + ConfiguredKeyValues[Folder] + " (exception occured)");
                }


                ConsoleService.WriteToConsole("finished FTPService Service");

                return(true);
            }
            catch (Exception ex)
            {
                ConsoleService.WriteToConsole("Exception occured");
                ConsoleService.WriteToConsole(ex.ToString());
            }
            finally
            {
                SaveLogs(targetFolder);
            }
            return(false);
        }