2 .net c# ftp ftp-client ftpwebrequest
我需要从 C# 代码将文件夹(包含子文件夹和文件)从一台服务器上传到另一台服务器。我做了一些研究,发现我们可以使用 FTP 来实现这一点。但这样我就只能移动文件,而不能移动整个文件夹。感谢这里的任何帮助。
(以及.NET框架中的任何其他FTP客户端FtpWebRequest)确实没有对递归文件操作(包括上传)的任何明确支持。您必须自己实现递归:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
有关创建文件夹的复杂代码背景,请参阅:
如何检查 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);
Run Code Online (Sandbox Code Playgroud)
如果您不需要递归上传,则有一个更简单的变体:
使用 WebClient 将文件目录上传到 FTP 服务器
或者使用可以自行递归的 FTP 库。
例如,使用WinSCP .NET 程序集,您可以通过一次调用上传整个目录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();
}
Run Code Online (Sandbox Code Playgroud)
该Session.PutFilesToDirectory方法默认是递归的。
(我是WinSCP的作者)