Uploading and Deleting files through FTP
In this article I am showing you to upload and delete files using File Transfer Protoclol(FTP) in Asp.net.
For Uploading
private bool UploadToFTP(string strFTPFilePath, string strLocalFilePath, string strUserName, string strPassword)
{
try
{
//Create a FTP Request Object and Specfiy a Complete Path
FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(strFTPFilePath);
//Call A FileUpload Method of FTP Request Object
reqObj.Method = WebRequestMethods.Ftp.UploadFile;
//If you want to access Resourse Protected,give UserName and PWD
reqObj.Credentials = new NetworkCredential(strUserName, strPassword);
// Copy the contents of the file to the byte array.
byte[] fileContents = File.ReadAllBytes(strLocalFilePath);
reqObj.ContentLength = fileContents.Length;
//Upload File to FTPServer
Stream requestStream = reqObj.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)reqObj.GetResponse();
response.Close();
}
catch (Exception Ex)
{
Response.Write(Ex);
//throw Ex;
}
return true;
}
In this method there are four parameters. First is strFTPFilePath , which shows the path of file where it is to be upload, second is strLocalFilePath whis shows the local path of that file.Third and fourth are the username and password of FTP server.
for calling this method
UploadToFTP("ftp://209.44.125.59/html/file/images/" + fillename, path, "Userweb", "mnjioeewv!&%");
For Uploading
private void DeleteFTP(string strFTPFilePath, string strUserName, string strPassword)
{
FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.Create(strFTPFilePath);
requestFileDelete.Credentials = new NetworkCredential(strUserName, strPassword);
requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.GetResponse();
}
for calling this method
DeleteFTP("ftp://209.44.125.59/html/file/images/" + filename, "Userweb4729", "mnjioeewv!$%");
I hope this will help you in uploading and deleting files through FTP.
Thank you so much,,,The code works Perfectly,,
ReplyDelete