【问题标题】:Recursive upload to FTP server in C#在 C# 中递归上传到 FTP 服务器
【发布时间】:2020-07-10 12:02:56
【问题描述】:

我需要通过 C# 代码将一个文件夹(包含子文件夹和文件)从一台服务器上传到另一台服务器。我做了一些研究,发现我们可以使用 FTP 来实现这一点。但是这样我就只能移动文件而不是整个文件夹。任何帮助在这里表示赞赏。

【问题讨论】:

  • 安全性怎么样?它只是“内部”还是通过互联网?如果是互联网,您可能需要考虑更安全的解决方案(SFTP、FTPS、SCP...)
  • “我只能移动文件而不是整个文件夹” – 这不是真的。一般来说,任何文件协议都只能复制文件,不能复制文件夹。但它甚至是“复制文件夹”? => 在服务器上创建同名文件夹!并且任何文件协议都可以创建文件夹。
  • @Fildor 安全不是这里的问题。谢谢
  • 在这种情况下:马丁说的。您可以使用 CWD、RMD 和 MKD。请参阅RFC959 - FTP 第 47 页。然而,我想知道:为什么不使用网络共享而只使用文件系统 API 来移动?
  • 如果曾经可以使用网络共享,那么它显然是一种更简单的方法(请注意,使用文件系统API它是相同的,您可以只复制文件并重新创建文件夹 - 虽然显然有现成的工具可以为您做到这一点 - 但这与 FTP 或任何其他文件传输协议相同)。

标签: c# .net ftp ftp-client ftpwebrequest


【解决方案1】:

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

  • 列出本地目录
  • 迭代条目、上传文件并递归到子目录(再次列出它们等)
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);
    }
}

有关创建文件夹的复杂代码背景,请参阅:
How to check if an FTP directory exists

使用如下函数:

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);

一个更简单的变体,如果您不需要递归上传:
Upload directory of files to FTP server using WebClient


或者使用可以自行进行递归的 FTP 库。

例如使用WinSCP .NET assembly,您只需调用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 method 默认是递归的。

(我是 WinSCP 的作者)

【讨论】:

    猜你喜欢
    • 2011-02-19
    • 2011-11-14
    • 2016-11-26
    • 2023-04-10
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    相关资源
    最近更新 更多