什么是简单的方法来创建一个使用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似乎没有任何方法来实现这一目标。

有帮助吗?

解决方案

使用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);
        }
    }
}

其他提示

下面就是答案,如果你想创建嵌套目录

有没有干净的方法来检查,如果一个文件夹上的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...
            }
        }
    }

像这样:

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

(有些迟。如何奇数。)

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top