How to Upload a file to ftp server using a WebClient in C#
Today i want to discuss an article to upload a file to the ftpserver through webclient Class which is alternative to FileUpload Control. This is the one i want to discuss here in this Article with Code snippets
In General when we want to do a task to Upload a file to Server we choose to Fileupload Control in asp.net and there are many ways to Upload a file to the Server one way to do it is by through webclient Class , In many forum discussions / Questions many people asks how to Upload a file to the server without using FileUpload Control for that my Answer is WebClient Class.
The WebClient Class has a method Called Upload file.
WebClient.UploadFile(string, string)
WebClient.UploadFile(URI, string)
WebClient.UploadFile(STRING, string,STRING)
WebClient.UploadFile(URI, string,STRING)
Here is the below Piece of Code to Upload a file to the Server
System.Net.WebClient wc = new System.Net.WebClient();
try
{
string fileName = "xyz.xls";
fullpath = @"C:\Users\enterpi\Desktop\" + fileName;
wc.UseDefaultCredentials = true;
wc.Credentials = new System.Net.NetworkCredential("username", "password");
byte[] responseBinary = wc.UploadFile("ftp://xxxx/xxxxx" + DateTime.Now.Millisecond + fileName, fullpath);
}
catch (System.Exception ex)
{
}
finally
{
wc.Dispose();
}
}
}
Here in the above Code you look Carefully .UseDefaultCredentials is a property in the Webclient Class this attribute is set to true and Wc.Credentials you need to set your ftp server Username and Password and UploadFile method you need to pass ftp url with the Filename and another argument is where you are fetching the File (i.e. source of the File).
The Code will Works fine it is tested in real time scenario.....