This article will explain how to upload your file to server using FTP details.
I am a programmer having intermediate level of experience in .NET development. One fine day, I was asked to create a scheduler program which would create a file and upload that to the server using FTP details. I started developing the code by using
StreamWriter class, suddenly I stopped..., thinking of why I am using
StreamWriter class as it is just to write a file, and my problem was to upload a file. Then after some R&D, I got the class which helped me to upload the file.
Using the Code
In order to upload a file using FTP details, one should know the server’s FTP URL, FTP username and FTP password.
We can achieve the file uploading task by using the below three inbuilt classes of .NET:
To start with the coding part.
First we need to import the below namespaces
Then we need to declare four variables as below:
String sourcefilepath = "@absolutepath";
String ftpurl = "@ftpurl";
String ftpusername = "@ftpusername";
String ftppassword = "@ftppassword";
Note: Please replace @absolutepath, @ftpurl, ftpusername, @ftppassword with your actual values.
Copy the below code and paste in your class:
private static void UploadFileToFTP(string source)
string filename = Path.GetFileName(source);
string ftpfullpath = ftpurl;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
catch (Exception ex)
The final point will be calling the above procedure by using the below code on whatever event you want the operation to be performed.
And we are done...
Points of Interest
I got an opportunity to learn about the below classes: