Site icon port135.com

How to upload a file via FTP in C#

I will be showing how to upload a file via FTP by using .NET Framework’s native libraries.

The libraries we need are:

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

The code block to upload a file (“tmp.csv” in my example):

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://your-ftp-address//the-folder-if-you-want//tmp.csv");
request.Method = WebRequestMethods.Ftp.UploadFile;

request.Credentials = new NetworkCredential("username", "password");

byte[] fileData = File.ReadAllBytes("C:\\Users\\sourcefolder\\tmp.csv");
request.ContentLength = fileData.Length;

Stream requestStream = request.GetRequestStream();
requestStream.Write(fileData, 0, fileData.Length);
requestStream.Close();

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

MessageBox.Show("Upload File Complete, status {0}", response.StatusDescription);

response.Close();
Exit mobile version