[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Upload files to an FTP server in C#

[Upload files to an FTP server in C#]

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 = (FtpWebRequest)WebRequest.Create(to_uri); 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); 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 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.