How can I get the length of a remote file??

How can I get the length of a remote file For example, the url is www.abc.com/abc.rar , I want to know the length(bytes) of the file abc.rar, how to do that You would say just download it, clearly I don't like that way. Any help will be appreciated!


Answer this question

How can I get the length of a remote file??

  • Bryce Beagley

    WebClient wc = new WebClient();

    Stream stm = wc.OpenRead(www.abc.com/abc.rar);

    Console.WriteLine("stm.length");

    This code segment didn't work and throwed an exception.



  • Kjell Tangen

    UP!

  • Rasmus Helwigh

    what was the exception We need as much details as possible :-)

    What type of method is "OpenRead" on the WebClient class

    I guess another way would be to use a WebRequest/WebResponse class to retrieve the file size but maybe overkill if functionality exists in the WebClient class



  • DaveDB

    This worked for me

    private int GetFileSize(String url)
    {
    try
    {
    Uri Url = new Uri(url);

    // Create a 'HttpWebrequest' object with the specified Uri.
    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(Url);

    // Send the 'HttpWebRequest' and wait for response.
    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

    // Release resources of response object.
    myHttpWebResponse.Close();

    // return the content length og the file
    return (int)myHttpWebResponse.ContentLength;
    }
    catch (WebException e)
    {
    MessageBox.Show(String.Format("\r\nWebException thrown.The Reason for failure is : {0}", e.Status));
    return -1;
    }
    catch (Exception e)
    {
    MessageBox.Show(String.Format("\nThe following Exception was raised : {0}", e.Message));
    return -1;
    }
    }


  • Kenster

    The Stream object returned by the WebClient.OpenRead() method doesn't support seeking and thus not the Length property. Download is all you can do. For example:

    WebClient wc = new WebClient();
    Stream stm = wc.OpenRead("http://www.google.com/index.html");
    byte[] buf = new byte[1024];
    int len = 0;
    int cnt = buf.Length;
    while (cnt == buf.Length) {
    cnt = stm.Read(buf, 0, cnt);
    len += cnt;
    }
    stm.Close();
    Console.WriteLine("{0}", len);



  • How can I get the length of a remote file??