2011年1月24日 星期一

如何檢查圖檔是否存在遠端主機

最近負責的案子,有些圖檔是來自遠端的Web主機,使用者希望如果遠端圖檔不存在時能以自訂的預設圖檔取代,以下的程式正是因應此需求

步驟1.
using System.Net;

步驟2
public static bool CheckWebReference(string url)
{
bool exists = false;
WebRequest request = WebRequest.Create(url);
request.Proxy = null;

try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
exists = true;
response.Close();
}
catch
{
exists = false;
}
request.Abort();
return exists;
}

上方的url是要檢查的網路資源網址,ex: http://xxx.xxx.xxx/xxx/xxx.png