Upload text into a file on an FTP server in C#

[Upload text]

The following FtpUploadString method uploads a text string into a file on 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 transfer a file.
private void FtpUploadString(string text, string to_uri,
    string user_name, string password)
{
    // Get the object used to communicate with the server.
    FtpWebRequest request =
        (FtpWebRequest)WebRequest.Create(to_uri);
    request.Method = WebRequestMethods.Ftp.UploadFile;

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

    // Write the text's bytes into the request stream.
    request.ContentLength = text.Length;
    using (Stream request_stream = request.GetRequestStream())
    {
        byte[] bytes = Encoding.UTF8.GetBytes(text);
        request_stream.Write(bytes, 0, text.Length);
        request_stream.Close();
    }
}

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 sets the request’s ContentLength property to the length of the text to be uploaded and gets a request stream that it can use to write the text. This is a plain Stream object, so it doesn’t provide handy methods such as WriteLine. Instead the code must convert the text into an array of bytes and write them into the stream. After it’s done, the code closes the stream.

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

When the main program calls this method, it adds the current date and time to the text you enter so you can tell that the uploaded text is new if you upload it multiple times.


Download Example   Follow me on Twitter   RSS feed   Donate




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

One Response to Upload text into a file on an FTP server in C#

  1. Jimmy says:

    Thank you Rod. Your code snippet works perfectly. Great job!

Leave a Reply

Your email address will not be published. Required fields are marked *