user516883
user516883

Reputation: 9398

asp.net how to check if a file exist on external server given web address

in my asp.net application, I would like to check to see if a file exist on an external server given the file address such as www.example.com/image.jpg. I tried File.exist and that does not seem to work. Thanks for any help.

Upvotes: 1

Views: 5653

Answers (3)

pricco
pricco

Reputation: 2783

You could use:

 bool exist = false;
 try
 {
      HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create("http://www.example.com/image.jpg");
      using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
      {
           exist = response.StatusCode == HttpStatusCode.OK;
      }
 }
 catch
 {
 }

Upvotes: 4

Yahia
Yahia

Reputation: 70379

try

((HttpWebResponse)((HttpWebRequest) WebRequest.Create ("http://www.example.com/image.jpg")).GetResponse ()).StatusCode  == HttpStatusCode.OK

IF the above evaluates to true then the file exists...

Upvotes: 1

Tieson T.
Tieson T.

Reputation: 21236

One obvious answer I can think of is to issue a request for the resource, and then study the response code sent back to your application. The article found at http://madskristensen.net/post/Get-the-HTTP-status-code-from-a-URL.aspx has a concise example of how to do so.

Upvotes: 0

Related Questions