Tag Archives: FtpWebRequest
Download file from FTP
I’ve created a simple method for you that will download a file from an FTP server and save it in the location you wish.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | private void DownloadFtpFile(string url, string savePath) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url); request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential("ftp username", "ftp password"); request.UseBinary = true; using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { using (Stream rs = response.GetResponseStream()) { using (FileStream ws = new FileStream(savePath, FileMode.Create)) { byte[] buffer = new byte[2048]; int bytesRead = rs.Read(buffer, 0, buffer.Length); while (bytesRead > 0) { ws.Write(buffer, 0, bytesRead); bytesRead = rs.Read(buffer, 0, buffer.Length); } } } } } |
Keep in mind that ideally you will want to do some error catching for cases that the file does not exist or the server is down and so on.
Simply call the method as follows:
1 | DownloadFtpFile("ftp://example.com/path_to_my_image_or_file.jpg", "C:\\location_and_name_of_file.jpg"); |
Posted in C#.
Tagged C#, csharp, ftp, ftp download file, FtpWebRequest, FtpWebResponse, snippet, winforms