C# 我可以检查一个文件是否存在于一个 URL 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1979915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:22:22  来源:igfitidea点击:

can I check if a file exists at a URL?

c#file-io

提问by mrblah

I know I can locally, on my filesystem, check if a file exists:

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

if(File.Exists(path))

Can I check at a particular remote URL?

我可以检查特定的远程 URL 吗?

采纳答案by Justin Rusbatch

If you're attempting to verify the existence of a web resource, I would recommend using the HttpWebRequestclass. This will allow you to send a HEADrequest to the URL in question. Only the response headers will be returned, even if the resource exists.

如果您正在尝试验证 Web 资源的存在,我建议您使用HttpWebRequest该类。这将允许您向HEAD相关 URL发送请求。即使资源存在,也只会返回响应头。

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

Of course, if you want to download the resource if it exists it would most likely be more efficient to send a GETrequest instead (by not setting the Methodproperty to "HEAD", or by using the WebClientclass).

当然,如果您想下载存在的资源,那么发送GET请求很可能会更有效(通过不将Method属性设置为"HEAD",或使用WebClient类)。

回答by Oded

If you are using a unc path or a mapped drive, this will work fine.

如果您使用的是 unc 路径或映射驱动器,这将正常工作。

If you are using a web address (http, ftp etc) you are better off using WebClient- you will get a WebException if it doesn't exist.

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

回答by cregox

If you want to just copy & paste Justin's code and get a method to use, here's how I've implemented it:

如果您只想复制并粘贴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;
    }
}

I'll keep his observation:

我会保留他的观察:

If you want to download the resource, and it exists, it would be more efficient to send a GETrequest instead by not setting the Methodproperty to "HEAD"or by using the WebClientclass.

如果您想下载资源并且它存在,那么GET通过不将Method属性设置为"HEAD"或使用WebClient类来发送请求会更有效。

回答by Kavit Trivedi

Below is a simplified version of the code:

下面是代码的简化版本:

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

回答by azouin

Anoter version with define timeout :

另一个版本定义超时:

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

回答by LastEnd

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

回答by Andrew

My version:

我的版本:

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

回答by nap

WebRequest will waiting long time(ignore the timeout user set) because not set proxy, so I change to use RestSharp to do this.

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;