ColdFusion & .NET: Using FTP to Upload a File

Our next little topic in the series comparing ColdFusion and .NET will cover the simple task of uploading a file via FTP.  This task is fairly easy in both languages as you will see below.

We will look at the ColdFusion code first.  ColdFusion includes the handy CFFTP tag to handle all of our FTP operations.  To upload a file you will follow three steps: opening the FTP connection, transferring the file and finally closing the FTP connection.

<code lang="cfm[lines]"><cfftp action="open" connection="ftpConn" password="FTPpassword" server="FTPserver" stoponerror="Yes" username="FTPusername"></cfftp>

Next is the .NET version of our code to accomplish the same task.  I have wrapped the core code into a function for code resuse.  You will then see how you simply call the function and pass it the data you need.

<code lang="csharp[lines]"> using System;<br></br>
using System.Net;<br></br> using System.IO;

public partial class uploadfile : System.Web.UI.Page
{
protected void Page
Load(object sender, EventArgs e)
{
ftpUpload("harvick.jpg", "YOUR LOCAL FILE PATH", "FTPserver", "FTPusername", "FTPpassword");
}

static void ftpUpload(string filename, string localPath, string host, string un, string pw)
{
FileInfo fileInf = new FileInfo(localPath + filename);
string uri = "ftp://" + host + "/" + fileInf.Name;
FtpWebRequest reqFTP;

// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create
(new Uri("ftp://" + host + "/" + fileInf.Name));

// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(un, pw);

// By default KeepAlive is true, where the control connection
// is not closed after a command is executed.
reqFTP.KeepAlive = false;

// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

// Specify the data transfer type.
reqFTP.UseBinary = false;

// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;

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

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

// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();

// Read from the file stream 2kb at a time
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 the file stream and the Request Stream
strm.Close();
fs.Close();
}
}

The .NET code seems a bit longer due to the commenting.  But as you can see, both languages make upload a file a very simple task.

Comments

comments powered by Disqus