Use FTP to get a file's 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.


// 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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.