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.

3 Responses 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!

  2. Oli Gerbi says:

    Thank you so much for this. Works almost like a charm for me xD I have the problem that I download the content of a file on a webserver, replace lines 4 and 5 inside it and upload the content again. Now it seems the download works fine and also the variable containing the updated content has everything in it, but after uploading it, the last one or two characters are missing. As it’s an .htaccess file containing ip adresses, that’s kinda not very good, is it 🙂 The file on the server and the newly generated file are in UTF-8.

    Can it be a mistake on the following two rows somewhere?
    > byte[] bytes = Encoding.UTF8.GetBytes(resultingTxt);
    > req_stream.Write(bytes, 0, resultingTxt.Length);

    Would it help to add some number to one of those to increase the amount of data that is being uploaded? How would i do it as it’s about bytes and stuff where I do not rly have an idea. Can I just add number 1 or 2 to bytes to write or what can I do?

    • RodStephens says:

      It works for me. I’m not sure why it wouldn’t work for you.

      You could try omitting the call to request_stream.Close. When the using block ends, the program will call the stream’s Dispose method, and that should force it to release all resources and then close. Or you could try calling the stream’s Flush method before calling Close.

      I wouldn’t think that would be necessary. Close should clean up the stream for you, but it’s worth a try.

      Let us know if that works.

Leave a Reply

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