C# Library - Uploading file to Server By FTP
How to Upload Files with FTP
In my previous article I explained about ASP.Net - Upload file & Download file from folder, Verification and Validation Upload File Type and File Size - ASP .Net.
In this article I will explain how to upload file to FTP server with valid credentials. To upload a file using ftp you show have following details like FTP URL, FTP UserName, FTP Password. To achieve the file uploading task we have three inbuilt classes in .Net:-
- FtpWebRequest
- WebRequestMethods
- NetworkCredential
Find the source code below:-
string vStatus = UploadFileToFTP.UploadFileToFTPST(vFileName,
vFilePath);
-----
public class UploadFileToFTP
{
public static string
UploadFileToFTPST(string pFileName, string pFilePath)
{
var
vFTPLocation = ConfigurationManager.AppSettings["DBServerFTP"]; //<add
key="DBServerFTP" value="ftp://192.168.1.108"/>
var
vFTPUser = ConfigurationManager.AppSettings["DBServerFTPUser"]; //<add key="DBServerFTPUser"
value="lepton"/>
var
vFTPPwd = ConfigurationManager.AppSettings["DBServerFTPPwd"]; //<add key="DBServerFTPPwd"
value="lepton"/>
//
Getting object used to communicate with the server.
FtpWebRequest
vFTPRequest = (FtpWebRequest)WebRequest.Create(vFTPLocation + "/" + pFileName);
vFTPRequest.Method = WebRequestMethods.Ftp.UploadFile;
//
Loggin-In Anonymously and passing user eMailId as password
vFTPRequest.Credentials = new NetworkCredential(vFTPUser,
vFTPPwd);
// Copy
the contents of the file to the request stream.
StreamReader
sourceStream = new StreamReader(pFilePath
+ "\\" + pFileName);
byte[]
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
vFTPRequest.ContentLength =
fileContents.Length;
Stream
requestStream = vFTPRequest.GetRequestStream();
requestStream.Write(fileContents,
0, fileContents.Length);
requestStream.Close();
FtpWebResponse
response = (FtpWebResponse)vFTPRequest.GetResponse();
return
response.StatusDescription;
}
}
Please leave your comments, suggestions and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!
C# Library - Uploading file to Server By FTP
Reviewed by Ravi Kumar
on
8:10 PM
Rating:

Post Comment
No comments: