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

Ok, so I already can upload a file to an FTP server: How to upload a file to an FTP server using C#?

However, now I need to create a directory first.

It follows some basic steps:

  1. Open a request using the full destination ftp path: Ftp://Ftp.Server.tld/ or Ftp://Ftp.Server.tld/Some/Path
  2. Configure the connection request
  3. Call GetResponse() method to actually attempt to create the directory
  4. Verify that it worked.

See the steps inside the source as comments:

using System;
using System.IO;
using System.Net;

namespace CreateDirectoryOnFtpServer
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateDirectoryOnFTP("ftp://ftp.server.tld", /*user*/"User1", /*pw*/"Passwd!", "NewDirectory");

        }

        static void CreateDirectoryOnFTP(String inFTPServerAndPath, String inUsername, String inPassword, String inNewDirectory)
        {
            // Step 1 - Open a request using the full URI, ftp://ftp.server.tld/path/file.ext
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(inFTPServerAndPath + "/" + inNewDirectory);

            // Step 2 - Configure the connection request
            request.Credentials = new NetworkCredential(inUsername, inPassword);
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = false;

            request.Method = WebRequestMethods.Ftp.MakeDirectory;

            // Step 3 - Call GetResponse() method to actually attempt to create the directory
            FtpWebResponse makeDirectoryResponse = (FtpWebResponse)request.GetResponse();
        }
    }
}

All right, now you have created a directory on the FTP server.


Copyright ® Rhyous.com – Linking to this page is allowed without permission and as many as ten lines of this page can be used along with this link. Any other use of this page is allowed only by permission of Rhyous.com.

Leave a Reply