Saturday, May 17, 2008

FTP file upload with C#

Same as for ftp file download, To upload a file to a ftp server C# provides easy functionality with use of System.Net namespaces.

Following code is a method built upon that which uses FtpWebRequest to upload a file to a ftp server. We are using File streams as well and thats "using System.IO;".

You can download my sample visual studio solution (project) for FTP Uploads/Downloads at my web site [www.thekalana.net\downloads.html]

It is noticed that some proxy connections that allow ftp download not always allows ftp uploads. If you have trouble getting things working... check with that too.
Sample Source Code :

// Dont forget to add: using System.Net;

// SET THESE PARAMETERS FIRST

string ftpServerIP = "0.0.0.0"; // replace with your ftp server IP Address

string ftpUserID = "user"; // ftp server username

string ftpPassword = "password"; // ftp server password

///

/// Method for uploading a file to the specified FTP Server

///

/// - file name of local file

public void Upload(string filename)

{

FileInfo fileInf = new FileInfo(filename);

string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

FtpWebRequest reqFTP;

// Create FtpWebRequest object from the Uri

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

// Provide WebPermission Credintials

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

// By default KeepAlive is true, control connection is kept alive

reqFTP.KeepAlive = false;

// FTP Command to be executed.

reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

// Data transfer type.

reqFTP.UseBinary = true;

// Notify the server - size of the uploaded file

reqFTP.ContentLength = fileInf.Length;

// Buffer size - 2kb

int buffLength = 2048;

byte[] buff = new byte[buffLength];

int contentLen;

// Open file stream (System.IO.FileStream) to read the file to be uploaded

FileStream fs = fileInf.OpenRead();

try

{

// Stream to which the file to be upload is written

Stream strm = reqFTP.GetRequestStream();

// Read from the file stream at above mentioned buffer size rate

contentLen = fs.Read(buff, 0, buffLength);

// till Stream content ends

while (contentLen != 0)

{

// Write Content from the file stream to the FTP Upload Stream

strm.Write(buff, 0, contentLen);

contentLen = fs.Read(buff, 0, buffLength);

}

// Close file stream

// Close Request Stream

strm.Close();

fs.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, "Upload Error");

}

}

No comments: