如何在C#中正确使用sftp上传文件夹和文件?

问题描述 投票:-1回答:1

SshNet使用SFTP上传一些文件,但是我在寻找正确创建目录的方法时遇到了问题。我刚刚发现我创建了一些spaguetti代码,我想知道是否有人可以帮助我完成这项任务,所以会非常感谢。

using Renci.SshNet;
using System;
using System.IO;
using System.Configuration;

namespace SFTPNamespace
{
    class mySFTPClass
    {
        public static void CrazySFTP(string pathRemoteFile, string pathLocalFile, Action<ulong> downloadCallback = null)
        {
            string[] folders = Directory.GetFileSystemEntries(pathLocalFile, "*.", SearchOption.AllDirectories);
            string[] txtfiles = Directory.GetFileSystemEntries(pathLocalFile, "*.txt", SearchOption.AllDirectories);
            string[] entries = Directory.GetFileSystemEntries(pathLocalFile, "*.*", SearchOption.AllDirectories);
            int totalCount_folders= folders.Length;
            int totalCount_entries = entries.Length;
            int totalCount_txtfiles = txtfiles.Length;
            Console.Write("Found #"
                + totalCount_entries +  " files which  #"
                + totalCount_folders + " are dirs and #" 
                + totalCount_txtfiles + " are txt files.\n" );
            string myServer= ConfigurationManager.AppSettings["Server"];
            int myPort= int.Parse(ConfigurationManager.AppSettings["Port"]);
            string myUser= ConfigurationManager.AppSettings["User"];
            string myPassword= ConfigurationManager.AppSettings["Password"];
            Console.Write("Trying to connect to the server. \n");
            try
            {
                using (SftpClient sftp = new SftpClient(myServer, myPort, myUser, myPassword))
                {
                    sftp.Connect();
                    if (sftp.IsConnected)
                    {
                        Console.Write("Connection okay.\n");
                        foreach (string folder in folders)
                        {
                            string folderDirectory = Path.GetDirectoryName(folder);
                            folderDirectory = folderDirectory.Replace("C:", "").Replace("local", "").Replace("path", "").Replace("\\", "");
                            string folderName = Path.GetFileName(folder);
                            if (sftp.Exists("/remote/path/" + folderName))
                            {
                                Console.Write("Dir already exists.\n");
                            }
                            else
                            {
                                Console.Write("Creating directory in : /remote/path/" + folderDirectory + "/" + folderName + ".\n");
                                sftp.CreateDirectory("/remote/path/" + folderDirectory + "/" + folderName);
                            }
                        }
                        foreach (string txtfile in txtfiles)
                        {
                            string txtDirectory = Path.GetDirectoryName(txtfile);
                            txtDirectory = txtDirectory.Replace("C:\\local\\path\\", "").Replace("\\", "/");                            
                            string txtName = Path.GetFileName(txtfile);                            
                            if (sftp.Exists("/remote/path/" + txtDirectory + "/" + txtName))
                            {
                                Console.Write("File already exists.\n");
                            }
                            else
                            {
                                Console.Write("Writing files in : /remote/path/" + txtDirectory + "/" + txtName + "\n");
                                using (FileStream fileStream = new FileStream(txtfile, FileMode.Open))
                                {
                                    sftp.BufferSize = 4 * 1024;
                                    sftp.UploadFile(fileStream, "/remote/path/" + txtDirectory + "/" + txtfile, true, null);
                                }
                            }
                        }
                        Console.Write("Files uploaded successfully.\n");
                        Console.Write("Disconnecting from server.\n");
                        sftp.Disconnect();
                    }
                    else
                    {
                        Console.Write("Connection error.\n");
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message + ".\n");
            }
        }
        static void Main(string[] args)
        {
            CrazySFTP(@"/remote/path/", @"C:\local\path\");
            Console.Write("Press a key to exit cli.\n");
            Console.ReadLine();
        }
    }
}

-编辑-现在可以了,但是它崩溃了,但是抛出了很多异常,我找不到找到答案的理由,当我得到答案时,我会跳回来并返回]

c# sftp daemon
1个回答
0
投票

我在解决如何解决问题时遇到问题,但是如果有人遇到此问题,这里就是解决方案,只需阅读代码并更改您的需求即可。

using Renci.SshNet;
using Renci.SshNet.Common;
using System;
using System.IO;
using System.Configuration;

namespace SFTP_UploadFiles
{
    class SFTP_Upload_Files
    {
        public static string Server = ConfigurationManager.AppSettings["SFTP_Server"];
        public static int Port = int.Parse(ConfigurationManager.AppSettings["SFTP_Port"]);
        public static string User = ConfigurationManager.AppSettings["SFTP_User"];
        public static string Password = ConfigurationManager.AppSettings["SFTP_Password"];

        public static string local_path = ConfigurationManager.AppSettings["SFTP_PATH_LOCAL"];

        public static void cargar_SFTP(string pathRemoteFile, string pathLocalFile)
        {
            string[] folders = Directory.GetFileSystemEntries(pathLocalFile, "*.", SearchOption.AllDirectories);
            string[] txtfiles = Directory.GetFileSystemEntries(pathLocalFile, "*.txt", SearchOption.AllDirectories);
            string[] entries = Directory.GetFileSystemEntries(pathLocalFile, "*.*", SearchOption.AllDirectories);
            int totalCount_folders= folders.Length;
            int totalCount_entries = entries.Length;
            int totalCount_txtfiles = txtfiles.Length;
            Console.Write("Found #"
                + totalCount_entries +  " elements which #"
                + totalCount_folders + " are directories and #" 
                + totalCount_txtfiles + " are text files.\n" );

            Console.Write("Initializing connection to SFTP\n");
            try
            {
                /* USE THIS IF YOUR SFTP NEEDS THIS SETTINGS */
                /*
                KeyboardInteractiveAuthenticationMethod keybAuth = new KeyboardInteractiveAuthenticationMethod(SFTP_User);
                keybAuth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(HandleKeyEvent);
                ConnectionInfo conInfo = new ConnectionInfo(SFTP_Server, SFTP_Port, SFTP_User, keybAuth);
                */

                using (SftpClient sftp = new SftpClient(Server, Port, User, Password))
                {
                    sftp.Connect();
                    if (sftp.IsConnected)
                    {
                        Console.Write("Console connected to SFTP Server.\n");                  
                        foreach (string folder in folders)
                        {
                            string folderDirectory = Path.GetDirectoryName(folder);
                            folderDirectory = folderDirectory.Replace("C:", "").Replace("local", "").Replace("pathDirectoryNames", "").Replace("\\", "");
                            string folderName = Path.GetFileName(folder);
                            if (String.IsNullOrEmpty(folderDirectory))
                            {

                            }
                            else
                            {
                                folderDirectory = folderDirectory + "/";
                            }
                            if (sftp.Exists("/path/remote/path/" + folderDirectory + folderName))
                            {
                                Console.Write("Directory already exists.\n");
                            }
                            else
                            {
                                string rutaDirectorio = "/remote/path/folder/" + folderDirectory + folderName;
                                string rutaDirectorioProcesados = "/remote/path/folder/directory/" + folderDirectory + folderName;
                                Console.Write("Creating directory in: /remote/path/folder/" + folderDirectory + folderName + "\n");
                                sftp.CreateDirectory(rutaDirectorio);
                            }
                        }
                        foreach (string txtfile in txtfiles)
                        {
                            string txtDirectory = Path.GetDirectoryName(txtfile);
                            string txtDirectoryReal = txtDirectory.Replace(@"C:\local\path", "").Replace("\\","/");
                            string txtName = Path.GetFileName(txtfile);
                            if (String.IsNullOrEmpty(txtDirectoryReal))
                            {                                
                            }
                            else
                            {
                                txtDirectoryReal = txtDirectoryReal + "/";
                            }

                            if (sftp.Exists("/remote/path/toCopyFiles/" + txtDirectoryReal + txtName) && (sftp.Exists("/remote/path/processed/files/" + txtDirectoryReal + txtName)))
                            {
                                Console.Write("File already exists.\n");
                            }
                            else
                            {
                                using (FileStream fileStream = new FileStream(txtfile, FileMode.Open))
                                {
                                    string rutaRemota = "/remote/path/toCopyFiles" + txtDirectoryReal + txtName;
                                    string rutaRemotaProcesados = "/remote/path/processed/files" + txtDirectoryReal + txtName;
                                    sftp.BufferSize = 4 * 1024;
                                    sftp.UploadFile(fileStream, rutaRemota, true, null);
                                    Console.Write("Writing file in : " + rutaRemota + "\n");
                                }
                            }
                        }
                        Console.Write("Files uploaded successfully.\n");
                        Console.Write("Files copy success.\n");
                        Console.Write("Disconnecting console.\n");
                        sftp.Disconnect();
                    }
                    else
                    {
                        Console.Write("Error, can't connect to the server.\n");
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message + ".\n");
            }
        }

        private static void HandleKeyEvent(object sender, AuthenticationPromptEventArgs e)
        {
            foreach (AuthenticationPrompt prompt in e.Prompts)
            {
                if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
                {
                    prompt.Response = Password;
                }
            }
        }

        static void Main(string[] args)
        {
            cargar_SFTP(@"/remote/path/test/", @local_path);
            Console.Write("Press any key to close CLI.\n");
            Console.ReadLine();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.