Tag Archives: ftp
Upload file to FTP
This is a simple method that will allow you to upload a file of your choice to an FTP server.
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 26 | private void UploadFtpFile(string filePath, string url) { FileInfo fileInfo = new FileInfo(filePath); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential("ftp username", "ftp password"); request.UseBinary = true; request.ContentLength = fileInfo.Length; using (FileStream fs = fileInfo.OpenRead()) { byte[] buffer = new byte[2048]; int bytesSent = 0; int bytes = 0; using (Stream stream = request.GetRequestStream()) { while (bytesSent < fileInfo.Length) { bytes = fs.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, bytes); bytesSent += bytes; } } } } |
Keep in mind that you will want to do some error catching to ensure that the file exists, the server is responding and so on.
Simply call the method as follows:
1 | UploadFtpFile("C:\\file_to_upload.jpg", "ftp://example.com/myfolder/name_of_file.jpg"); |
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