Checks if the remote file exists

Language: C#

/// <summary>Get remote file information</summary>
/// <param name="url">The URL of the remote file</param>
/// <returns>RemoteFile if the remote file exists, or null</returns>
public static RemoteFile RemoteFileInfo(string url) {
    RemoteFile file = new RemoteFile();
    try {
        var request = WebRequest.Create(url);
        request.Method = "HEAD";
        using (var response = request.GetResponse() as HttpWebResponse) {
            file.LastModified = response.LastModified;
            file.Size = response.ContentLength;
            file.StatusCode = response.StatusCode;
            file.ContentType = response.ContentType;
            file.ContentEncoding = response.ContentEncoding;
        }
    }
    catch(Exception e) {
        return null;
    }
    return file;
}

public class RemoteFile {
    public DateTime LastModified { get; set; }
    public long Size { get; set; }
    public HttpStatusCode StatusCode { get; set; }
    public string ContentType { get; set; }
    public string ContentEncoding { get; set; }
}

 142 total views

Author: Albert

Leave a Reply