我需要从一个服务器通过C#代码将一个文件夹(包含子文件夹和文件)上传到另一台服务器。我进行的研究很少,发现可以使用FTP来实现。但是这样我就只能移动文件,而不能移动整个文件夹。感谢您的帮助。
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
上传整个目录:
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();
}
默认是递归的。
(我是WinSCP的作者)