2011-09-18 53 views
2

我正在嘗試做一個簡單的函數來驗證網站上是否存在特定的文件。驗證文件存在於網站上

web請求被設置爲頭這樣我就可以得到,而不是將整個文件下載文件長度,但我得到「無法連接到遠程服務器」異常。 如何驗證網站上存在的文件?

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(); 

編輯:我的壞,事實證明我檢查日誌後我的防火牆阻止http請求。 它沒有提示我一個例外規則,所以我認爲這是一個錯誤。

+2

你知不知道你在說Web服務器是否真正支持HEAD請求?您是否嘗試過使用Wireshark來查看網絡級別發生了什麼? –

+2

我剛剛使用隨機URL測試了您的代碼片段,並且它可以正常工作。你確定你指定的網址實際上存在嗎? –

+0

我同意@Jon,OP應該用GET替代來看看會發生什麼。 –

回答

0
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); 
    } 
} 
1

我測試過這一點,它工作正常:

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(); 
     } 
    } 
} 

試試這個網址:http://www.centrosardegna.com/images/losa/losaabbasanta.png然後修改圖像名稱,它會返回false。 ;-)