这是我为自己创建的一个方法,它看起来像是在做你正在寻找的事情。
private bool FileExists(string url, out int contentLength)
{
bool fileExistsAnswer;
try
{
WebRequest request = HttpWebRequest.Create(url);
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)
{
fileExistsAnswer = true;
contentLength = Convert.ToInt32(response.ContentLength);
}
else
{
fileExistsAnswer = false;
contentLength = 0;
}
}
}
catch(Exception Ex)
{
fileExistsAnswer = false;
contentLength = 0;
}
return fileExistsAnswer;
} // private bool FileExists(string url)
我就是这样用的。
string productThumbUrl = string.Empty;
int contentLength;
if (FileExists(productThumbUrl_png, out contentLength))
{
productThumbUrl = productThumbUrl_png;
}