HttpWebRequest and Multiple Files

I’m working on a project at work right now to pull inventory data from the bookstore’s point-of-sale system into the e-commerce site I’m setting up for them. One of the parts in the process is to check the web server for any new/updated images for the items on the website. I am doing a web request for each image on the server to see if I really does exist. After doing so many, I noticed that all of the files kept coming back saying they weren’t there, when I know darn well they are! So after a little research online, I noticed that you need to close your Response object when you are finished with it.

Here’s my code:

private static bool _FileExists(string filename) {
    try {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(filename);
        req.Timeout = 5000;
        req.Method = "HEAD";
        HttpWebResponse response = (HttpWebResponse)req.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK) {
            response.Close();    // IMPORTANT
            return true;
        } else {
            response.Close();    // IMPORTANT
            return false;
        }
    } catch(Exception ex) {
        return false;
    }
}

The big thing to note here is when I’m calling response.Close(), as that closes out the connection. So if you are experiencing issues where you keep getting time out errors, give this a try. Here’s the original article that helped me.