4

I need to check if a text file exists on a site on a different domain. The URL could be:

http://sub.somedomain.com/blah/atextfile.txt

I need to do this from code behind. I am trying to use the HttpWebRequest object, but not sure how to do it.

EDIT: I am looking for a light weight way of doing this as I'll be executing this logic every few seconds

3 Answers 3

2
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
                       "http://sub.somedomain.com/blah/atextfile.txt");

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
    // FILE EXISTS!
}
response.Close();
Sign up to request clarification or add additional context in comments.

6 Comments

You might also want to set the HttpWebRequest.Timeout property to a low value, if you're doing it every few seconds. The default is 100 seconds, you probably don't want to wait that long if the file is unavailable or server is unresponsive.
It appears that requestGetResponse() throws an exception if the file does not exist? The remote server returned an error: (404) Not Found.","StackTrace":" at System.Net.HttpWebRequest.GetResponse
I'm guessing this could be wrapped in a using block to make it a little mo' nice (no Close() required).
@User102533: what's the exception? That could be your answer right there.
I'm guessing it's just a generic "WebException". Is that good enough? Or do you really need to know if the file isn't there, and take a different action if the server returns some other kind of error?
|
0

You could probably use the method used here:

http://www.eggheadcafe.com/tutorials/aspnet/2c13cafc-be1c-4dd8-9129-f82f59991517/the-lowly-http-head-reque.aspx

Comments

0

Something like this might work for you:

using (WebClient webClient = new WebClient())
{
    try
    {
        using (Stream stream = webClient.OpenRead("http://does.not.exist.com/textfile.txt"))
        {
        }
    }
    catch (WebException)
    {
        throw;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.