If the file is small, the easiest way is WebClient.DownloadData :
WebClient client = new WebClient(); string url = "ftp://ftp.example.com/remote/path/file.zip"; client.Credentials = new NetworkCredential("username", "password"); byte[] contents = client.DownloadData(url);
If the file is a text file, use WebClient.DownloadString :
string contents = client.DownloadString(url);
The contents of the file are assumed to be UTF-8 encoded (a simple ASCII file will also be used). If you need to use a different encoding, use the WebClient.Encoding property .
If the file is large, so you need to process it in chunks, instead of loading it into the whole memory, use FtpWebRequest :
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Ftp.DownloadFile; using (Stream stream = request.GetResponse().GetResponseStream()) { byte[] buffer = new byte[10240]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { // process the chunk in "buffer" } }
If the large file is a text file and you want to process it line by line rather than pieces of a fixed size, use StreamReader :
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.txt"); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Ftp.DownloadFile; using (Stream stream = request.GetResponse().GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { while (!reader.EndOfStream) { string line = reader.ReadLine(); // process the line Console.WriteLine(line); } }
Again, this assumes UTF-8 encoding. If you want to use a different encoding, use the StreamReader contructor overload, which also accepts Encoding .
Martin Prikryl
source share