Friday, January 30, 2009

How to upload File on FTP Server in .Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace PubishApps
{
/************************************************
* Topic : How to upload File on FTP Server in .Net
* Reference Required: System.Net.
* Author : kalit sikka
* Summary: using FtpWebRequest Class in System.Net namespace to upload files on local machine to FTP Server.
* **********************************************/
public struct FTPCredentials
{
public string FTPHostID;
public string UserName;
public string Password;
public FTPCredentials(string HostID, string User, string Password)
{
this.FTPHostID = HostID;
this.UserName = User;
this.Password = Password;
}
}
public class DataUploadOnFTP
{
private string FTPHostID = string.Empty;
private string UserName = string.Empty;
private string Password = string.Empty;
private string FullPathOfInputFile = string.Empty;
private string FileName = string.Empty;
///
/// Constructor
///

/// FTP Credentials
/// Full path on Input File
public DataUploadOnFTP(FTPCredentials Credentials, string FullPathOfFileToUpload)
{
FTPHostID = Credentials.FTPHostID;
UserName = Credentials.UserName;
Password = Credentials.Password;
this.FullPathOfInputFile = FullPathOfFileToUpload;
// Getting only File Name from complete address
this.FileName = System.IO.Path.GetFileName(FullPathOfFileToUpload);
}
///
/// Method to upload file to FTP Server.
///

///
public bool UploadFileOnFTP()
{
try
{
string FTPHost = "ftp://" + FTPHostID;
string FTPFilePath = Path.Combine(FTPHost, FileName);
FtpWebRequest oFTP = (FtpWebRequest)FtpWebRequest.Create(FTPFilePath);
oFTP.Credentials = new NetworkCredential(UserName, Password);
oFTP.KeepAlive = true;
oFTP.UseBinary = true;
oFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(FullPathOfInputFile);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = oFTP.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
return true;
}catch(Exception e)
{
return false;
}
}
}
}

No comments:

Post a Comment

Locations of visitors to this page