Home >Backend Development >C++ >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:
<code class="language-csharp">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; } }</code>
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!