How to create a directory on an FTP server using C #?

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

I figured out how to upload a file to an existing folder, for example:

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 that the file is not available. I suppose this is because before I upload my file I need to create a new folder, but WebClient does not seem to have methods for this.

+61
c # ftp webclient
May 13, '09 at 21:57
source share
4 answers

Use FtpWebRequest using the WebRequestMethods.Ftp.MakeDirectory method.

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); } } } 
+103
May 13 '09 at 10:03 p.m.
source share

Here is the answer if you want to create subdirectories

There is no clean way to check if a folder exists on ftp, so you need to loop and create the entire nested structure into one folder at a time

 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... } } } 
+33
May 7 '14 at 13:51
source share

Something like that:

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

(a little late, how strange.)

+19
May 13, '09 at 10:04
source share

Creating an FTP directory can be difficult, as you need to check if the destination folder exists or not. You may need to use the FTP library to check and create the directory. You can take a look at this: http://www.componentpro.com/ftp.net/ and this example: http://www.componentpro.com/doc/ftp/Creating-a-new-directory-Synchronously.htm

-one
Mar 17 '15 at 2:40
source share



All Articles