66

使用 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似乎没有任何方法可以实现这一点。

4

4 回答 4

110

使用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);
        }
    }
}
于 2009-05-13T22:03:35.803 回答
41

如果要创建嵌套目录,这是答案

没有干净的方法来检查 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...
            }
        }
    }
于 2014-05-07T13:51:16.227 回答
20

像这样的东西:

// remoteUri points out an ftp address ("ftp://server/thefoldertocreate")
WebRequest request = WebRequest.Create(remoteUri);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
WebResponse response = request.GetResponse();

(有点晚了。真奇怪。)

于 2009-05-13T22:04:38.610 回答
-1

创建 FTP 目录可能很复杂,因为您必须检查目标文件夹是否存在。您可能需要使用 FTP 库来检查和创建目录。你可以看看这个: http: //www.componentpro.com/ftp.net/这个例子: http: //www.componentpro.com/doc/ftp/Creating-a-new-directory-Synchronously .htm

于 2015-03-17T02:40:44.947 回答