問題描述
我需要通過 C# 代碼將一個文件夾(包含子文件夾和文件)從一臺服務(wù)器上傳到另一臺服務(wù)器.我做了一些研究,發(fā)現(xiàn)我們可以使用 FTP 來實(shí)現(xiàn)這一點(diǎn).但是這樣我就只能移動文件而不是整個文件夾.任何幫助在這里表示贊賞.
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 客戶端)確實(shí)沒有任何明確支持遞歸文件操作(包括上傳).您必須自己實(shí)現(xiàn)遞歸:
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);
}
}
有關(guān)創(chuàng)建文件夾的復(fù)雜代碼的背景,請參閱:
如何檢查FTP目錄是否存在
使用如下函數(shù):
string sourcePath = @"C:sourcelocalpath";
// root path must exist
string url = "ftp://ftp.example.com/target/remote/path/";
NetworkCredential credentials = new NetworkCredential("username", "password");
UploadFtpDirectory(sourcePath, url, credentials);
一個更簡單的變體,如果您不需要遞歸上傳:
使用WebClient將文件目錄上傳到FTP服務(wù)器
A simpler variant, if you do not need a recursive upload:
Upload directory of files to FTP server using WebClient
或者使用可以自行進(jìn)行遞歸的 FTP 庫.
Or use FTP library that can do the recursion on its own.
例如,使用 WinSCP .NET 程序集,您只需調(diào)用一次即可上傳整個目錄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:sourcelocalpath", "/target/remote/path").Check();
}
Session.PutFilesToDirectory
方法默認(rèn)是遞歸的.
The Session.PutFilesToDirectory
method is recursive by default.
(我是 WinSCP 的作者)
這篇關(guān)于在 C# 中遞歸上傳到 FTP 服務(wù)器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!