Upload files to an FTP server in C#

[Upload files]

The following FtpUploadFile method uploads a file to an FTP server. The to_uri parameter is a URI (Uniform Resource Identifier) that identifies the target file as in ftp://www.somewhere.com/test.txt. The other parameters are self-explanatory.

// Use FTP to upload a file.
private void FtpUploadFile(string filename, string to_uri,
    string user_name, string password)
    // Get the object used to communicate with the server.
    FtpWebRequest request =
    request.Method = WebRequestMethods.Ftp.UploadFile;

    // Get network credentials.
    request.Credentials =
        new NetworkCredential(user_name, password);

    // Read the file's contents into a byte array.
    byte[] bytes = System.IO.File.ReadAllBytes(filename);

    // Write the bytes into the request stream.
    request.ContentLength = bytes.Length;
    using (Stream request_stream = request.GetRequestStream())
        request_stream.Write(bytes, 0, bytes.Length);

The code starts by creating a WebRequest object associated with the URI and by setting its Method property to UploadFile.

Next the program creates a NetworkCredentials object to identify the account being used to upload the file. The example shown in the picture assumes you are using anonymous FTP. If you are using a username and password, fill them in on the main form.

The code uses System.IO.File.ReadAllBytes to read the file’s contents into a byte array and sets the requests object’s ContentLength property to the length of the text to be uploaded. It gets a request stream that it can use to write into the request and writes the bytes into it. After it’s done, the code closes the stream.

Note that this method overwrites existing files on the FTP server without warning.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in files, ftp, internet, web and tagged , , , , , , , , , , , , , . Bookmark the permalink.