Follow us on X (Twitter)  Like us on Facebook  Connect with us on LinkedIn  Subscribe to our YouTube Channel  Subscribe to our WhatsApp Group

Many time we need to programmatically retrieve the size of a file before downloading it from a web location or a network path. This is require to calculate the progress and/or the estimated time to download and display it to the user. For a local file it is easy, but to retrieve this information from a remote location, the implementation is little different.

 

Today in this small blog post, we will learn how to retrieve it dynamically using C# code. Continue reading to know about it. Code snippet has been shared in the post.

 

Retrieve file size from a remote URL using C# (www.kunal-chowdhury.com)

 

The system API class “System.Net.HttpWebRequest” allows you to retrieve the file information programmatically. The size of each file/page generally available in the header section of web response, which you can query to get it. Before getting the web response from the web request, set the method of the request to “HEAD”.

 

Header contains “Content-Length” property value which gives you the size of the file in bytes. This you can later calculate to convert in MB or GB. Here is the code snippet for you to refer:

 

private static string GetFileSize(Uri uriPath)
{
    var webRequest = HttpWebRequest.Create(uriPath);
    webRequest.Method = "HEAD";
 
    using (var webResponse = webRequest.GetResponse())
    {
       var fileSize = webResponse.Headers.Get("Content-Length");
       var fileSizeInMegaByte = Math.Round(Convert.ToDouble(fileSize) / 1024.0 / 1024.0, 2);
       return fileSizeInMegaByte + " MB";
    }
}

 

I hope that the post will help you to programmatically retrieve the details/file size of the remote file. Let me know, if you have any queries.

Have a question? Or, a comment? Let's Discuss it below...

dhgate

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.