递归上传到C#中的FTP服务器 [英] Recursive upload to FTP server in C#

查看:179
本文介绍了递归上传到C#中的FTP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从一个服务器通过C#代码将一个文件夹(包含子文件夹和文件)上传到另一台服务器。我进行的研究很少,发现可以使用FTP来实现。但是这样我就只能移动文件,而不能移动整个文件夹。感谢您的帮助。

I would need to upload a folder (which contains sub folders and files) from one server to another from C# code. I have done few research and found that we can achieve this using FTP. But with that I am able to move only files and not the entire folder. Any help here is appreciated.

推荐答案

FtpWebRequest (以及.NET框架中的任何其他FTP客户端) )的确对递归文件操作(包括上传)没有任何显式支持。您必须自己实现递归:

The FtpWebRequest (nor any other FTP client in .NET framework) indeed does not have any explicit support for recursive file operations (including uploads). You have to implement the recursion yourself:


  • 列出本地目录

  • 迭代条目,上传文件并递归到子目录(再次列出它们,等等)

void UploadFtpDirectory(string sourcePath, string url, NetworkCredential credentials)
{
    IEnumerable<string> files = Directory.EnumerateFiles(sourcePath);
    foreach (string file in files)
    {
        using (WebClient client = new WebClient())
        {
            Console.WriteLine($"Uploading {file}");
            client.Credentials = credentials;
            client.UploadFile(url + Path.GetFileName(file), file);
        }
    }

    IEnumerable<string> directories = Directory.EnumerateDirectories(sourcePath);
    foreach (string directory in directories)
    {
        string name = Path.GetFileName(directory);
        string directoryUrl = url + name;

        try
        {
            Console.WriteLine($"Creating {name}");
            FtpWebRequest requestDir = (FtpWebRequest)WebRequest.Create(directoryUrl);
            requestDir.Method = WebRequestMethods.Ftp.MakeDirectory;
            requestDir.Credentials = credentials;
            requestDir.GetResponse().Close();
        }
        catch (WebException ex)
        {
            FtpWebResponse response = (FtpWebResponse)ex.Response;
            if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                // probably exists already
            }
            else
            {
                throw;
            }
        }

        UploadFtpDirectory(directory, directoryUrl + "/", credentials);
    }
}

在创建复杂代码的背景下文件夹,请参阅:

如何检查FTP目录是否存在

使用类似函数:

string sourcePath = @"C:\source\local\path";
// root path must exist
string url = "ftp://ftp.example.com/target/remote/path/";
NetworkCredential credentials = new NetworkCredential("username", "password");

UploadFtpDirectory(sourcePath, url, credentials);

如果不需要递归上载,则是一个更简单的变体:

< a href = https://stackoverflow.com/q/44012637/850848>使用WebClient将文件目录上传到FTP服务器

A simpler variant, if you do not need a recursive upload:
Upload directory of files to FTP server using WebClient

或使用可以自己执行递归的FTP库。

Or use FTP library that can do the recursion on its own.

例如,使用 WinSCP .NET程序集,您只需一次调用 Session.PutFilesToDirectory

For example with WinSCP .NET assembly you can upload whole directory with a single call to the Session.PutFilesToDirectory:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "ftp.example.com",
    UserName = "username",
    Password = "password",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Download files
    session.PutFilesToDirectory(@"C:\source\local\path", "/target/remote/path").Check();
}

Session.PutFilesToDirectory 方法默认为递归。

The Session.PutFilesToDirectory method is recursive by default.

(我是WinSCP的作者)

这篇关于递归上传到C#中的FTP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆