[C# Helper]
Index Books FAQ Contact About Rod
[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]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

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

Title: Get file size and last modification time on an FTP server in C#

[Get file size and last modification time on an FTP server in C#]

The FtpGetFileSize method shown in the following code gets a file's size in bytes. The uri parameter gives the full path to the file as in ftp://www.somewhere.com/test.txt. Note that the URI must begin with ftp not http.

// Use FTP to get a remote file's size. private long FtpGetFileSize(string uri, string user_name, string password) { // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Ftp.GetFileSize; // Get network credentials. request.Credentials = new NetworkCredential(user_name, password); try { using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { // Return the size. return response.ContentLength; } } catch (Exception ex) { // If the file doesn't exist, return -1. // Otherwise rethrow the error. if (ex.Message.Contains("File unavailable")) return -1; throw; } }

This code creates an FtpWebRequest object to work with the file. It sets the request's Method property to GetFileSize and gets a response. The only trick here is that the file's size is returned through the response's ContentLength property.

The FtpGetFileTimestamp method shown in the following code gets a file's creation date and time.

// Use FTP to get a remote file's timestamp. private DateTime FtpGetFileTimestamp(string uri, string user_name, string password) { // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Ftp.GetDateTimestamp; // Get network credentials. request.Credentials = new NetworkCredential(user_name, password); try { using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { // Return the size. return response.LastModified; } } catch (Exception ex) { // If the file doesn't exist, return Jan 1, 3000. // Otherwise rethrow the error. if (ex.Message.Contains("File unavailable")) return new DateTime(3000, 1, 1); throw; } }

This code creates an FtpWebRequest object, sets its Method property to GetDateTimestamp, and gets a response. The trick here is that the file's timestamp is returned through the response's LastModified property.

Download the example to experiment with it and to see additional details.

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