tags:

views:

4130

answers:

2

What's an easy way to create a directory on an FTP server using C#?

I figured out how to upload a file to an already existing folder like this:

using (WebClient webClient = new WebClient())
{
    string filePath = "d:/users/abrien/file.txt";
    webClient.UploadFile("ftp://10.128.101.78/users/file.txt", filePath);
}

However, if I want to upload to users/abrien, I get a WebException saying the file is unavailable. I assume this is because I need to create the new folder before uploading my file, but WebClient doesn't seem to have any methods to accomplish that.

+8  A: 

Use FtpWebRequest, with a method of WebRequestMethods.Ftp.MakeDirectory.

For example:

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);
        }
    }
}
Jon Skeet
Any ideas on how to do this through an HTTP proxy? (not supported by FtpWebRequest)
Jonas Elfström
Not really, I'm afraid. From what I remember of my days working on HTTP proxies, they translate HTTP methods into FTP commands - and I can't think of an equivalent HTTP method :(
Jon Skeet
@Jon Skeet : Is it possible to create nested directories with one WebRequest? I am trying to make "ftp://host.com/ExistingFolder/new1/new2", but I am getting "WebException - 550" (File not found, no access) and don't know weather this is the reason.
Rekreativc
A: 

Something like this:

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

(a bit late. how odd.)

Fredrik Mörk