Practical Approach of Uploading File to FTP Path


In this article we are going to see how to upload a file to a FTP path and save it.

Steps to upload a file to FTP:

  1. Create a FTP web request.
  2. Create an output File stream and select the FTP destination path to store.
  3. Get Response from Request.
  4. Write the output file stream to the FTP path.
  5. Now the file is uploaded to the FTP path and placed in the specified path.

Step 1: Used Namespaces:

using System.Net;
using System.IO;

Step 2: Usage:

FTPUpload("C:\\default.aspx", "ftp://208.43.121.51/", "UserName", "Password");

Step 3: Creating NetworkCredential means passing username and password of FTP path

 /// <summary>
 /// NetworkCredential just to set the User and password of ftp path.
 /// </summary>
 public static NetworkCredential CreateNetworkCredentials(string ftpUserID, string ftpPassword)
{
    return new NetworkCredential(ftpUserID, ftpPassword);
}


Step 4: Creating FTP web Request:

/// <summary>
///
Creates the FTP web request
/// </summary>
public static FtpWebRequest CreateFTPRequest(string fullFtpPath, string fileName)
{
    return (FtpWebRequest)FtpWebRequest.Create(new Uri(fullFtpPath + "/" + fileName));
}


Step 5: Upload File to FTP path:

//Upload into the ftp path.
public static void FTPUpload(string fileNamePath, string fullFtpPath,
string ftpUserID, string ftpPassword)
{
    FileStream outputStream;

    //Now the FTP web request completed and ready for response.
    FtpWebRequest ftpWebRequest = GetFTPWebRequest(fileNamePath, fullFtpPath, ftpUserID, ftpPassword, out outputStream);

    //Getting response from the request.
    FtpWebResponse response = (FtpWebResponse)ftpWebRequest.GetResponse();
    PassStreamDataToFileStream(response, outputStream);
}

Step 6: Setting Web Request and returning it:

//Download
public static FtpWebRequest GetDownloadFTPWebRequest(string path, string fileName, string fullFtpPath,
string ftpUserID, string ftpPassword, out FileStream fs)
{
    //Creates file stream based on the passed path.
    fs = new FileStream(path + "\\" + fileName, FileMode.Create);

    //Creating FTP request.
    FtpWebRequest reqFTP = CreateFTPRequest(fullFtpPath, fileName);

    //Setting FTP Credentials.
    reqFTP.Credentials = CreateNetworkCredentials(ftpUserID, ftpPassword);
    reqFTP.KeepAlive = false;

    // What mechanism you need to perform like download,upload etc in the FTP path.
    reqFTP.Method = WebRequestMethods.Ftp.UploadFile
    ;

    // Specify the data transfer type.
    reqFTP.UseBinary = true;

    // Notify the server about the size of the uploaded file
    reqFTP.ContentLength = fs.Length;

    return reqFTP;
}


Opens a file stream (System.IO.FileStream) to read the file to be uploaded

public static FileStream GetFileStream(string path, out long contentLength, out FileInfo fileInfo)
{
    fileInfo = GetFileInfo(path);
    contentLength = fileInfo.Length;
    return fileInfo.OpenRead();
}


Step 7: Used to get file information:

public static FileInfo GetFileInfo(string path)
{
    return new FileInfo(path);
}


Step 8: Creating the response to write if an error occurs:

/// <summary>
///
Get current response.
/// </summary>
public static HttpResponse GetHttpResponse()
{
    return HttpContext.Current.Response;
}


Step 9: Writing the stream as a file into the FTP path:

//This is used for the Upload Purpose.
public static void PassStreamDataToFileStream(FtpWebResponse response, FileStream fs)
{
    try
    {
        Stream stream = response.GetResponseStream();
        int buffLength = 2048; // The buffer size is set to 2kb
        byte[] buff = new byte[buffLength];
        int contentLen;

        // Stream to which the file to be upload is written
        // Read from the file stream 2kb at a time.
        contentLen = fs.Read(buff, 0, buffLength);

        // Till Stream content ends.
        while (contentLen != 0)
        {
            // Write Content from the file stream to the FTP Upload Stream
            stream.Write(buff, 0, contentLen);
            contentLen = fs.Read(buff, 0, buffLength);
        }

        // Close the file stream and the Request Stream.
        stream.Close();
        fs.Close();
        response.Close();
    }
    catch (Exception ex)
    {
        GetHttpResponse().Write(ex.Message + " Upload Error");
    }
}


Thanks for reading this article. Have a nice day.

Up Next
    Ebook Download
    View all
    Learn
    View all