title: Does a web file exist - using same function to get the Content Type
body: <p>I have a function that is coded to get the <code>Content-Type</code> of a web file.</p>
  
  <p>Here is the function:</p>
  
  <pre><code>public string GetContentTypeOfUri(string uri)
  {
      try
      {
          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
          request.Method = "HEAD";
          using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
          {
              var contentType = response.Headers["Content-Type"];
              return (contentType);
          }
      }
      catch (Exception ex)
      {
          return "error";
      }
  }
  </code></pre>
  
  <p>Rather than writing a whole different function to detect if a web file exists, how can I calculate if a file exists from the same code as used to get the <code>Content-Type</code>?</p>
  
  <p>If I use a uri of a file that does not exist, an exception occurs. The ex.HResult equals -2146233079 when this exception occurs, with a message = "The remote name could not be resolved: '[address name]'".</p>
  
  <p>Is it safe to say that when an exception occurs, and the ex.HResult equals -2146233079, the file does not exist?</p>
  
  <p>Is there an easier/better way to work this out?</p>
  
  <p>Thanks in advance</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Here is the <code>HttpClient</code> code that I have:</p>
  
  <pre><code>public async Task&lt;string&gt; GetContentTypeAsync(string uri)
  {
      using (var httpClient = new HttpClient())
      {
          var request = new HttpRequestMessage(HttpMethod.Post, uri);
          request.Method = new HttpMethod("HEAD");
          var response = await httpClient.SendAsync(request);
          string contentType = response.Content.Headers.ContentType.ToString();
          return contentType;
      }
  }
  </code></pre>
  
  <p>Your example web address does inform me that the address does not exist, however, if I have a web address that does not exist such as <a href="http://www.usa.canon.com/app/html/HDV/HG10/images/hg10_sample_image_03.jpg5" rel="nofollow">http://www.usa.canon.com/app/html/HDV/HG10/images/hg10_sample_image_03.jpg5</a>, I am getting a StatusCode of OK, as a Text content type is returned as a custom error page.</p>