The question, “How can I FTP a binary file with AVR for .NET” has come up a time or two in tech support lately. Here is a quick and easy response to that question. As you’ll see, uploading a file with FTP with AVR for .NET is pretty simple.

The code in Figure 1 shows how to call the function, FtpUploadFile, that this article provides. FtpUploadFile needs five arguments:

In the example in Figure 1, the FTP server is at ftp://ftp.myftpserver.com and the folder for the uploaded file is “spreadsheets.” These two values comprise the first argument, with a slash (“/”) added between them. This argument can optionally end with a trailing slash (“/”).  In this example, the status value returned is either the text returned from the FTP operation or an exception message.

Figure 1. Uploading a file with FTP

The meat of this article is below in Figure 2. This is the function that does the heavy lifting of uploading a file with FTP.

Figure 2. FtpUploadFile function

At the core of the FtpUploadFunction are two objects in the System.Net namespace:

These methods were added with the .NET Framework version 2.0. The code shown here is for .NET Framework 4.0.

Here is a quick rundown of the major parts of FtpUploadFile:

Lines 16-19:

Ensure that the FtpUri ends with a slash (“/”) and then append the target file name (the name you want the uploaded file to have on the target computer).

Lines 20-22:

Set the properties of the request instance of the FtpWebRequest object.  In this case we’re setting the object to upload binary files and specifying the FTP login credentials.

Lines 24-25:

Read all bytes of the source file and into the fileContents byte array.

Lines 27-29:

Instance a requestStream (of type Stream) and write the contents of the fileContents byte array to it.

Lines 31-33

Invoke the upload, save its StatusDescription in the status variable, and close the response instance.

Lines 34-36:

If any exception was thrown, save the exception message to the status variable. For production work you might want to return an instance of a class with more information than this.

Lines 38:

Check out of this motel! You’re done.

That’s all there is to it. It’s short, sweet, and works like a champ!