MOCKSTACKS
EN
Questions And Answers

More Tutorials




Download FTP File in C#

To download an FTP File in C# you will need to have: IP/Host for server, path to file, filename, username and password. First you need to create OutputStream object to store the file locally using path and filename, then you need to create an FtpWebRequest object with URI sent through construutor, then set the Method property to WebRequestMethods.Ftp.DownloadFile, then set Credentials property to new NetworkCredential object with username and password passed as parameters, Finally get the response using GetResponse() method.

Example


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

public class Program
{
	public static void Main()
	{
		
		tr {
			string ftpUserID = "ftpUsername";
			string ftpPassword = "password";

			string ftpServerIP = "192.168.1.2";
			string filePath = @"\\path\to\file";
			string fileName = "filename";

			FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);

			FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
			reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
			reqFTP.UseBinary = true;
			reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
			FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
			Stream ftpStream = response.GetResponseStream();
			long cl = response.ContentLength;
			int bufferSize = 2048;
			int readCount;
			byte[] buffer = new byte[bufferSize];

			readCount = ftpStream.Read(buffer, 0, bufferSize);
			while (readCount > 0)
			{
				outputStream.Write(buffer, 0, readCount);
				readCount = ftpStream.Read(buffer, 0, bufferSize);
			}

			ftpStream.Close();
			outputStream.Close();
			response.Close();
		} catch (Exception ex) {
			Console.WriteLine("Error downloading file: " + ex.Message);
		}
	}
}

Conclusion

In this page (written and validated by ) you learned about Download FTP File in C# . What's Next? If you are interested in completing C# tutorial, we encourage you simply to start here: C# Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.