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:
- Create a FTP web request.
- Create an output File stream and select the FTP destination path to store.
- Get Response from Request.
- Write the output file stream to the FTP path.
- 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);

Join the conversation! Your thoughts help the community grow.