我需要从一个服务器通过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:
- 列出本地目录
- 迭代条目,上传文件并递归到子目录(再次列出它们,等等)
在创建复杂代码的背景下文件夹,请参阅: 如何检查FTP目录是否存在
使用类似函数:
string sourcePath = @"C:\source\local\path"; // root path must exist string url = "ftp://ftp.example/target/remote/path/"; NetworkCredential credentials = new NetworkCredential("username", "password"); UploadFtpDirectory(sourcePath, url, credentials);如果不需要递归上载,则是一个更简单的变体: 使用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", 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服务器
发布评论