Home > Backend Development > C++ > How to Check if a URL Exists in C#?

How to Check if a URL Exists in C#?

Susan Sarandon
Release: 2025-01-11 22:41:42
Original
315 people have browsed it

How to Check if a URL Exists in C#?

How to verify whether a URL exists in C#

Your code uses the WebClient class to retrieve data from the URL. However, when the user enters a stock symbol that does not exist, a runtime error is encountered. In order to solve this problem, you need a way to check if the URL is valid before trying to download it.

How to use HTTPWebRequest:

One way is to use the HttpWebRequest class. Here is an example implementation:

private bool RemoteFileExists(string url)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "HEAD";

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            return (response.StatusCode == HttpStatusCode.OK);
        }
    }
    catch
    {
        return false;
    }
}
Copy after login

This method sends an HTTP HEAD request to the URL. If the response code is 200 (OK), it means the file exists and is accessible. Otherwise, it returns false.

The above is the detailed content of How to Check if a URL Exists in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template