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"); |
Leave a Reply