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

[Get file size and last modification time]

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 Example   Follow me on Twitter   RSS feed   Donate








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

Leave a Reply

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