How to Check if a File Exists on a HTTPS Website

To check if a file exists on a HTTPS website using C#, you can use the HttpWebRequest class to send an HTTP HEAD request to the file URL and check the response status code. Here is an example code snippet:

string ImagePath = "https://www.example.com/files/example.pdf";

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ImagePath);

    request.Method = "HEAD";

    bool exists;

    try

    {

        request.GetResponse();

        exists = true;

    }

    catch

    {

        exists = false;

    }

In this code, we first create a HttpWebRequest object and set its method to "HEAD" to send an HTTP HEAD request to the file URL. Then, we use a try-catch block to handle any WebExceptions that may occur if the file URL is invalid or the server returns an error. Finally, we check the response status code to determine if the file exists or not.


Note that this code only checks if the file exists on the server, and does not download or access the file in any way.

Popular Posts