Uploading files to an FTP server

Below is the code which will upload files from server/local pc to FTP server, for full code refer to my previous post. link is given above.

public static void UploadFile(string fileName)
{
// Get the object used to communicate with the server.
FtpWebRequest reqObj = (FtpWebRequest) FtpWebRequest.Create(getServerUri() + fileName);

// Set the credentials
// This application reads the UserName & Password from settings file to logon to FTP site.
reqObj.Credentials = new NetworkCredential(FTPSettings.UserName, FTPSettings.Password);

// Turn off KeepAlive (will close connection on completion)
reqObj.KeepAlive = false;

// Specifying the data transfer type [binary].
reqObj.UseBinary = true;

// Define the action required (in this case, uploading a file).
reqObj.Method = WebRequestMethods.Ftp.UploadFile;

// The buffer size is set to 2kb
//int buffLength = 2048;
byte[] buffer = new byte[2048];
int contentLen;

// Opens a file stream (System.IO.FileStream) to read the file
// to be uploaded
FileStream fs = File.OpenRead(fileName);

try
{
// Stream to which the file to be upload is written
using( Stream requestStream = reqObj.GetRequestStream() )
{
try
{
// Read from the file stream 2kb at a time
contentLen = fs.Read(buffer, 0, buffer.Length);

// Till Stream content ends
while( contentLen != 0 )
{
// Write Content from the file stream to the FTP Upload
// Stream
requestStream.Write(buffer, 0, contentLen);
contentLen = fs.Read(buffer, 0, buffer.Length);
}
}
catch( Exception ex )
{
ErrorLog.LogError(ex);
}
// Close the file stream and the Request Stream
requestStream.Close();
}
fs.Close();
}
catch( Exception ex )
{
ErrorLog.LogError(ex.Message.ToString());
}
}


Comments

Author: Abhishek Arya25 Apr 2009 Member Level: Gold   Points : 0

that is really good one. i have used this one for my application too.

Author: Lakhan Pal23 Oct 2011 Member Level: Gold   Points : 0

Hi,

there is one more method to upload file to FTP server. single line of code to upload file:


My.Computer.Network.UploadFile(Source, Target, ftpUsername, ftpPassword)
[/CODE}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: