如何使用C#在ftp服务器上创建目录?

Ant*_*ien 61 .net c# ftp webclient

使用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);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我想上传到users/abrien,我会WebException说文件不可用.我认为这是因为我需要在上传文件之前创建新文件夹,但WebClient似乎没有任何方法可以实现.

Jon*_*eet 104

使用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是否可以使用一个WebRequest创建嵌套目录?我试图制作"ftp://host.com/ExistingFolder/new1/new2",但我得到"WebException - 550"(找不到文件,没有访问权限)并且不知道天气这是原因. (12认同)

Yan*_*ard 34

如果要创建嵌套目录,可以使用以下答案

没有干净的方法来检查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...
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,假设您使用的是较新的C#版本,则可以执行以下操作:在(ex.Response为FtpWebResponse ftpResponse && ftpResponse.StatusDescription.Contains(“文件存在”))时捕获(WebException ex) (2认同)

Fre*_*örk 20

像这样的东西:

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

(有点晚了.多奇怪.)

  • +1仅仅落后于Jon Skeet的第二名. (16认同)