This code sample shows how to use Asp.net with C# code to programmatically upload files to an ftp server.
if you want to upload file directly from
client side to ftp server then first you have to save that file on your
server through fileupload control and then use this code to upload that
file to ftp server.
/// Code to upload file to FTP Server
/// </summary>
/// <param name="strFilePath">Complete physical path of the file to be uploaded</param>
/// <param name="strFTPPath">FTP Path</param>
/// <param name="strUserName">FTP User account name</param>
/// <param name="strPassword">FTP User password</param>
/// <returns>Boolean value based on result</returns>
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 You need to give User Name 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)
{
// report error
throw Ex;
}
return true;
}
//Calling the Funtion:-
UploadToFTP("ftp://9.2.2.100/aa/samp.txt", Server.MapPath(@"File/Graph.xls"), "uid", "pwd");
//Or you can upload through WebClient here is code:-
private void UploadToFTPFromWEBCLIENT()
{
WebClient wc = new WebClient();
Uri uriadd = new Uri(@"ftp://9.2.2.100/aa/samp.txt");
wc.Credentials = new NetworkCredential("UName", "PWD");
wc.UploadFile(uriadd, Server.MapPath(@"File/Graph.xls"));
}
No comments:
Post a Comment