FTP fileupload using C Sharp NET

Here is the simple class file using which you can upload a file to the FTP using .NET class library. This class implements an FTP client.

class Upload
{
public static string uploadFile(string FTPAddress, string filePath, string FTPDir, string username, string password)
{
try
{

//Create FTP request
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + “/” + FTPDir + “/dshfksdhfkjsdhfkhs/” + Path.GetFileName(filePath));

request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;

//Load the file
FileStream stream = File.OpenRead(filePath);
byte[] buffer = new byte[stream.Length];

stream.Read(buffer, 0, buffer.Length);
stream.Close();

//Upload file
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();

return “1″;

}
catch (WebException exc)
{
return exc.Message;
}
finally
{ }
}

}

Mayur Gondaliya - CTO - CaseTronyx, Inc. Director - ExaSpring Information Services Pvt. Ltd. Web Investor. Software Engineer. Workaholic. Insomniac.

Leave a Reply