开发者

Check if a text file exists in ASP.NET

开发者 https://www.devze.com 2022-12-19 14:11 出处:网络
I need to check if a text file exists on a site on a different domain. The URL could be: http://sub.somedomain.com/blah/atextfile.txt

I need to check if a text file exists on a site on a different domain. The URL could be:

http://sub.somedomain.com/blah/atextfile.txt

I need to do this from code behind. I am trying to use the HttpWebRequest object, but not sure how to do it开发者_开发百科.

EDIT: I am looking for a light weight way of doing this as I'll be executing this logic every few seconds


HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
                       "http://sub.somedomain.com/blah/atextfile.txt");

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
    // FILE EXISTS!
}
response.Close();


You could probably use the method used here:

http://www.eggheadcafe.com/tutorials/aspnet/2c13cafc-be1c-4dd8-9129-f82f59991517/the-lowly-http-head-reque.aspx


Something like this might work for you:

using (WebClient webClient = new WebClient())
{
    try
    {
        using (Stream stream = webClient.OpenRead("http://does.not.exist.com/textfile.txt"))
        {
        }
    }
    catch (WebException)
    {
        throw;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消