Anuraj
Anuraj

Reputation: 19598

How can one check to see if a remote file exists using C#

How can I check a File exits in a web location in ASP.Net(in a different web application, but same web server), currently I doing like this. Is there any better way of doing this?

using (WebClient client = new WebClient())
{
            try
            {
                Stream stream = client.OpenRead("http://localhost/images/myimage.jpg");
                if (stream != null)
                {
                    //exists
                }
            }
            catch
            {
                //Not exists
            }
}

Upvotes: 0

Views: 3961

Answers (4)

ZombieSheep
ZombieSheep

Reputation: 29953

Remember that you are never going to get a 100% definitive response on the existence of a file, but the way I do it would be pretty similar to yours...

bool remoteFileExists(string addressOfFile)
{
    try
    {
        HttpWebRequest request = WebRequest.Create(addressOfFile) as HttpWebRequest;
        request.Method = "HEAD";
        request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
        var response = request.GetResponse() as HttpWebResponse;
        return (response.StatusCode == HttpStatusCode.OK);  
    }
    catch(WebException wex)
    {
        return false;
    }
}

EDIT :: looking at the edit by Anton Gogolev above (How can one check to see if a remote file exists using C#) I should have cast the response to a HttpWebResponse object and checked the status code. Edited the code to reflect that

Upvotes: 2

Anton Gogolev
Anton Gogolev

Reputation: 115751

If a file is accessible via HTTP, you can issue a HTTP HEAD requrest for that particular URL using HttpWebRequest. If HttpWebResponse.StatusCode will be 200, than file is there.

EDIT: See this on why GetResponse throws stupid exceptions when it actually should not do that.

Upvotes: 1

michele
michele

Reputation: 2091

You can use Server.MapPath to get the directory and then check if file exist using IO standard methods like File.Exists

Upvotes: 0

rahul
rahul

Reputation: 187040

The 404 or Not Found error message is a HTTP standard response code indicating that the client was able to communicate with the server but the server could not find what was requested. A 404 error indicates that the requested resource may be available in the future.

You can use a HEAD request (HttpWebRequest.Method = "HEAD")

Upvotes: -1

Related Questions