且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查文件是否存在于网络上

更新时间:2023-02-23 18:37:08

您只能验证是否可以访问网络上的文件.您永远不会知道文件是否不存在,因为尝试该服务时该服务可能会脱机,或者速度太慢,或者服务器出于安全原因拒绝响应您.

You can only verify whether you can acess to the file on the web.  You never know whether the file does not exist, because the service could be offline when you try it or it is just too slow, or the server refuses to response to you for security reasons.

您可以使用WebClient类或HttpWebRequest类.您的第一段代码很好,当HttpWebRequest.GetReponse无法连接到服务器或遇到其他网络问题时,它将引发异常.您需要将其放在try-catch块中并处理这些异常,这些异常将告诉您为什么您无法访问该文件.一种可能是文件不存在.

You can use either WebClient class or HttpWebRequest class.  First piece of your code is fine, the HttpWebRequest.GetReponse will throw exception when it fails to connect to the server or hits other network problems.  You need put it inside a try-catch block and handle those exceptions, those exception will tell you why you failed to access that file. One possiblity is that file does not exisit.