我知道我可以在我的文件系统上本地检查文件是否存在:
if(File.Exists(path))
Run Code Online (Sandbox Code Playgroud)
我可以查看特定的远程URL吗?
Jus*_*tch 81
如果您正在尝试验证是否存在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();
}
}
Run Code Online (Sandbox Code Playgroud)
当然,如果要下载资源(如果存在),则发送GET请求的效率可能更高(通过不设置Method属性"HEAD"或使用WebClient类).
cre*_*gox 16
如果你只想复制和粘贴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;
}
}
Run Code Online (Sandbox Code Playgroud)
我会保持他的观察:
如果要下载资源并且存在,则
GET通过不将Method属性设置为"HEAD"或使用WebClient该类来发送请求会更有效.
小智 9
以下是代码的简化版本:
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;
}
Run Code Online (Sandbox Code Playgroud)