使用C#在FTP服务器上创建目录的简单方法是什么?
我想出了如何将文件上传到现有的文件夹,如下所示:
using (WebClient webClient = new WebClient())
{
string filePath = "d:/users/abrien/file.txt";
webClient.UploadFile("ftp://10.128.101.78/users/file.txt", filePath);
}
但是,如果我要上传到users/abrien
,我会收到一个WebException
,说该文件不可用。我认为这是因为我需要在上传文件之前创建新文件夹,但WebClient
似乎没有任何方法可以实现这一点。
答案 0 :(得分:101)
使用FtpWebRequest
,方法为WebRequestMethods.Ftp.MakeDirectory
。
例如:
using System;
using System.Net;
class Test
{
static void Main()
{
WebRequest request = WebRequest.Create("ftp://host.com/directory");
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("user", "pass");
using (var resp = (FtpWebResponse) request.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
}
}
答案 1 :(得分:31)
如果您想创建嵌套目录
,这是答案没有干净的方法来检查ftp上是否存在文件夹,因此您必须循环并在当时创建所有嵌套结构文件夹
public static void MakeFTPDir(string ftpAddress, string pathToCreate, string login, string password, byte[] fileContents, string ftpProxy = null)
{
FtpWebRequest reqFTP = null;
Stream ftpStream = null;
string[] subDirs = pathToCreate.Split('/');
string currentDir = string.Format("ftp://{0}", ftpAddress);
foreach (string subDir in subDirs)
{
try
{
currentDir = currentDir + "/" + subDir;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(currentDir);
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(login, password);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
//directory already exist I know that is weak but there is no way to check if a folder exist on ftp...
}
}
}
答案 2 :(得分:19)
这样的事情:
// remoteUri points out an ftp address ("ftp://server/thefoldertocreate")
WebRequest request = WebRequest.Create(remoteUri);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
WebResponse response = request.GetResponse();
(有点晚。多奇怪。)
答案 3 :(得分:-1)
创建FTP目录可能很复杂,因为您必须检查目标文件夹是否存在。您可能需要使用FTP库来检查和创建目录。你可以看一下这个:http://www.componentpro.com/ftp.net/和这个例子:http://www.componentpro.com/doc/ftp/Creating-a-new-directory-Synchronously.htm