Verify file exists on website
I am attempting to make a simple function that verifies that a specific file exists on a website.
The web request is set to head so I can get the file length instead of downloading the entire file, but I get "Unable to connect to the remote server" exception. How can I verify a file exists on a website?
WebRequest w;
WebResponse r;
w = WebRequest.Create("http://website.com/stuff开发者_运维知识库/images/9-18-2011-3-42-16-PM.gif");
w.Method = "HEAD";
r = w.GetResponse();
edit: My bad, turns out my firewall was blocking http requests after I checked the log. It didnt prompt me for an exception rule so I assumed it was a bug.
I've tested this and it works fine:
private bool testRequest(string urlToCheck)
{
var wreq = (HttpWebRequest)WebRequest.Create(urlToCheck);
//wreq.KeepAlive = true;
wreq.Method = "HEAD";
HttpWebResponse wresp = null;
try
{
wresp = (HttpWebResponse)wreq.GetResponse();
return (wresp.StatusCode == HttpStatusCode.OK);
}
catch (Exception exc)
{
System.Diagnostics.Debug.WriteLine(String.Format("url: {0} not found", urlToCheck));
return false;
}
finally
{
if (wresp != null)
{
wresp.Close();
}
}
}
try it with this url: http://www.centrosardegna.com/images/losa/losaabbasanta.png then modify the image name and it will return false. ;-)
try
{
WebRequest request = HttpWebRequest.Create("http://www.microsoft.com/NonExistantFile.aspx");
request.Method = "HEAD"; // Just get the document headers, not the data.
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
// This may throw a WebException:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
// If no exception was thrown until now, the file exists and we
// are allowed to read it.
MessageBox.Show("The file exists!");
}
else
{
// Some other HTTP response - probably not good.
// Check its StatusCode and handle it.
}
}
}
catch (WebException ex)
{
// Cast the WebResponse so we can check the StatusCode property
HttpWebResponse webResponse = (HttpWebResponse)ex.Response;
// Determine the cause of the exception, was it 404?
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
MessageBox.Show("The file does not exist!");
}
else
{
// Handle differently...
MessageBox.Show(ex.Message);
}
}
精彩评论