簡體   English   中英

我可以檢查一個文件是否存在於一個 URL 中?

[英]can I check if a file exists at a URL?

我知道我可以在本地,在我的文件系統上,檢查文件是否存在:

if(File.Exists(path))

我可以檢查特定的遠程 URL 嗎?

如果您嘗試驗證 Web 資源是否存在,我建議您使用HttpWebRequest類。 這將允許您向相關 URL 發送HEAD請求。 即使資源存在,也只會返回響應頭。

var url = "http://www.domain.com/image.png";
HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";


try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
    /* A WebException will be thrown if the status of the response is not `200 OK` */
}
finally
{
    // Don't forget to close your response.
    if (response != null)
    {
        response.Close();
    }
}

當然,如果您想下載存在的資源,那么發送GET請求很可能會更有效(通過不將Method屬性設置為"HEAD" ,或使用WebClient類)。

如果您只想復制並粘貼Justin的代碼並獲得一種使用方法,那么我是如何實現它的:

using System.Net;

public class MyClass {
    static public bool URLExists (string url) {
        bool result = false;

        WebRequest webRequest = WebRequest.Create(url);
        webRequest.Timeout = 1200; // miliseconds
        webRequest.Method = "HEAD";

        HttpWebResponse response = null;

        try {
            response = (HttpWebResponse)webRequest.GetResponse();
            result = true;
        } catch (WebException webException) {
            Debug.Log(url +" doesn't exist: "+ webException.Message);
        } finally {
            if (response != null) {
                response.Close();
            }
        }

        return result;
    }
}

我會保留他的觀察:

如果您想下載資源並且它存在,則通過不將Method屬性設置為"HEAD"或使用WebClient類來發送GET請求會更有效。

下面是代碼的簡化版本:

public bool URLExists(string url)
{
    bool result = true;

    WebRequest webRequest = WebRequest.Create(url);
    webRequest.Timeout = 1200; // miliseconds
    webRequest.Method = "HEAD";

    try
    {
        webRequest.GetResponse();
    }
    catch
    {
        result = false;
    }

    return result;
}

如果您使用的是 unc 路徑或映射驅動器,這將正常工作。

如果您使用的是網址(http、ftp 等),最好使用WebClient - 如果它不存在,您將收到一個 WebException。

public static bool UrlExists(string file)
    {
        bool exists = false;
        HttpWebResponse response = null;
        var request = (HttpWebRequest)WebRequest.Create(file);
        request.Method = "HEAD";
        request.Timeout = 5000; // milliseconds
        request.AllowAutoRedirect = false;

        try
        {
            response = (HttpWebResponse)request.GetResponse();
            exists = response.StatusCode == HttpStatusCode.OK;
        }
        catch
        {
            exists = false;
        }
        finally
        {
            // close your response.
            if (response != null)
                response.Close();
        }
        return exists;
    }

我在asp.net core中遇到了同樣的問題,我已經用HttpClient解決了

private async Task<bool> isFileExist(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                var restponse = await client.GetAsync(url);

               return restponse.StatusCode == System.Net.HttpStatusCode.OK;
            }
        }

我的版本:

    public bool IsUrlExist(string url, int timeOutMs = 1000)
    {
        WebRequest webRequest = WebRequest.Create(url);
        webRequest.Method = "HEAD";
        webRequest.Timeout = timeOutMs;

        try
        {
            var response = webRequest.GetResponse();
            /* response is `200 OK` */
            response.Close();
        }
        catch
        {
            /* Any other response */
            return false;
        }

        return true;
    }

WebRequest 會等待很長時間(忽略用戶設置的超時時間),因為沒有設置代理,所以我改用 RestSharp 來做到這一點。

var client = new RestClient(url);
var request = new RestRequest(Method.HEAD);

 request.Timeout = 5000;
 var response = client.Execute(request);
 result = response.StatusCode == HttpStatusCode.OK;

感謝所有的答案。 我想添加我的實現,其中包括出現錯誤時的默認狀態,適用於像我這樣的特定情況。

private bool HTTP_URLExists(String vstrURL, bool vResErrorDefault = false, int vTimeOut = 1200)
{
   bool vResult = false;
   WebRequest webRequest = WebRequest.Create(vstrURL);
   webRequest.Timeout = vTimeOut; // miliseconds
   webRequest.Method = "HEAD";
   HttpWebResponse response = null;
   try
   {
      response = (HttpWebResponse)webRequest.GetResponse();
      if (response.StatusCode == HttpStatusCode.OK) vResult = true;
      else if (response.StatusCode == HttpStatusCode.NotFound) vResult = false;
      else vResult = vResErrorDefault;
   }
       catch (WebException ex)
           {
           
              if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
              {
                  var resp01 = (HttpWebResponse)ex.Response;
                  if (resp01.StatusCode == HttpStatusCode.NotFound)
                  {
                      vResult = false;
                  }
                  else
                     {
                         vResult = vResErrorDefault;
                     }
                 }
                 else
                     {
                         vResult = vResErrorDefault;
                     }
                 }
           finally
           {
               // Don't forget to close your response.
               if (response != null)
               {
                   response.Close();
               }
           }
           return vResult;
}

另一個版本定義超時:

public bool URLExists(string url,int timeout = 5000)
{
    ...
    webRequest.Timeout = timeout; // miliseconds
    ...
}

這對我有用:

bool HaveFile(string url)
        {
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.DownloadString(url);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM