C# Programming > Data

C# FTP Upload

C# ftp, ftp upload

Why FTP?

Using FTP to upload files in C# is a very simple and universal way to upload files (and download with FTP) from a webserver. Most servers today, free and paid for, have support for FTP uploading. All one needs is a username and password and the operation becomes quite simple.

Luckily the .NET Framework comes with built-in C# FTP upload support, which means no need for external libraries. Note that there are many free FTP dlls to use in C#. Some of them use more complex methods to connect to the server, but many also use this same simple structure.

The way in which the program will be structured, it will be relatively simple to expand its functionality.

Writing the .NET Uploader

The FTP Request

To connect to the FTP server we can use the FtpWebRequest C# object under the System.Net namespace. The object is created with the FtpWebRequest.Create() function. Note that the function will ask for a URL to connect to, the format to write the url is: [FTP Address] + "/" + [Filename of file to upload].

(Be careful not to use "//", double slashing is for "\", this double slash can cause problems with some servers.

Here is the code:

FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/" + 
Path.GetFileName(filePath));

As for setting up the object, the two most important settings are the Method and the Credentials settings:

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

Notice that to link the username and password combination we use the NetworkCredential object. Meanwhile the Method property tells the class we intend to use the FTP connection to upload a file.

Loading the File

The next step would be to transfer the upload file into a byte array which will be used for the FTP upload. A buffer array if you will. Here is a simple method to do it:

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


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

This way is simple since it reads the file all at once. For bigger files to upload it might be a good idea to load them by parts to make sure the program does not freeze. (Use a for loop and stick the link Application.DoEvents() in each iteration).

There is an almost limitless number of ways to read a file in C# so use what you like.

Page 2
Uploading the File >>

Back to C# Article List