Practical Approach of Creating and Removing Directory To/from FTP Path


In this article we are going to see how to create and remove a directory to/from FTP path.

Step 1: Used Namespaces:


using
System.Net;
using
System.IO;


Step 2: Usage:

MakeDir("ftp://208.43.121.51/","directory", "UserName", "Password");
RemoveDir
("ftp://208.43.121.51/","directory", "UserName", "Password");


Step 3: Creating Directory in FTP path:

/// <summary>
/// Used to create directory in the FTP path.
/// </summary>
public static void MakeDir(string fullFtpPath, string directoryName, string ftpUserID, string ftpPassword)
{
  FtpWebRequest reqFTP;
  try
{
  // dirName = name of the directory to create
      reqFTP = CreateFTPRequest(fullFtpPath, directoryName);
  //Setting Webrequest type.
      reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
  //Setting datatype for file transfer
      reqFTP.UseBinary = true;
  //Settting User credentials
      reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  //Getting response from request
      FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  //Helps to disconnect from the FTP path.
      Stream ftpStream = response.GetResponseStream();
   //Closes the Stream
       ftpStream.Close();
   //Closes the Response.
        response.Close();
 }
   catch (Exception ex)
{
   HttpContextClass.GetHttpResponse().Write(ex.Message);
}
}


Step 4: Removing Directory in FTP path:

/// <summary>
/// Used to Remove Directly from the FTP path.
/// </summary>
public static void RemoveDir(string fullFtpPath, string directoryName, string ftpUserID, string ftpPassword)
{
   FtpWebRequest reqFTP;
   try
{
 // dirName = name of the directory to create.
      reqFTP = CreateFTPRequest(fullFtpPath, directoryName);
 //Setting Webrequest type.
      reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
 //Setting datatype for file transfer
      reqFTP.UseBinary = true;
 //Settting User credentials
      reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
 //Getting response from request
       FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
 //Helps to disconnect from the FTP path.
       Stream ftpStream = response.GetResponseStream();
 //Closes the Stream
     ftpStream.Close();
 //Closes the Response.
     response.Close();
}
  catch (Exception ex)
{
  HttpContextClass.GetHttpResponse().Write(ex.Message);
}
}

Step 5:
Writing an error to response if any:

public static HttpResponse GetHttpResponse()
{
      return HttpContext.Current.Response;

}

Thanks for reading this article. Have a nice day.