How to connect remote SFTP from Azure web site scheduled job

后端 未结 1 2023
忘了有多久
忘了有多久 2021-01-06 20:46

I have one console app which will be scheduled as job in AZURE web site. From that console app I want to connect remote SFTP and get all files and save them in my folder ins

相关标签:
1条回答
  • 2021-01-06 20:51

    First of all best and free option to use in this case is WinSCP .NET assembly.

    You can download it from here

    So lets start this is the function:

    public static void GetSftp(string host, string user, string password, int port, string source, string dest, string remoteDest)
        {
    
            Directory.CreateDirectory(dest);
            var winScpSessionOptions = new SessionOptions
            {
                HostName = host,
                Password = password,
                PortNumber = port,
                UserName = user,
                Protocol = Protocol.Sftp,
                GiveUpSecurityAndAcceptAnySshHostKey = true
            };
    
            var session = new Session();
            session.Open(winScpSessionOptions);
    
            var remoteDirInfo = session.ListDirectory(remoteDest);
            foreach (RemoteFileInfo fileInfo in remoteDirInfo.Files)
            {
                if (fileInfo.Name.Equals(".") || fileInfo.Name.Equals("..")) { continue; }
                Console.WriteLine("{0}", remoteDest + fileInfo.Name);
                try
                {
    
                    var x = remoteDest +"/"+ fileInfo.Name;
                    var y = dest +"\\"+ fileInfo.Name; 
    
                    var result = session.GetFiles(x, y);
    
                    if (!result.IsSuccess)
                    {
    
                    }
                    else
                    {
                        session.RemoveFiles(remoteDest +"/"+ fileInfo.Name);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
    
            }
    
        }
    

    What this function does? It just gets SFTP credentials and login to SFTP .And lists all file names .And saves each file in AZURE web site ftp.After it removes transferred file.

    • source is SFTP folder
    • Destination where you want to transfer files from SFTP.In AZURE web sites it looks like this D:\home\site\wwwroot\YourFolderName
    0 讨论(0)
提交回复
热议问题