// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Net; namespace E { public enum WebTestResult { STATUS_EXIST, STATUS_NOT_EXIST, STATUS_NO_HOST, STATUS_NOT_HTTP } public class WebTest { public static WebTestResult Exist(string url) { try { WebRequest wreq = WebRequest.Create(url); wreq.Method = "HEAD"; WebResponse wresp = wreq.GetResponse(); if(wresp is HttpWebResponse) { HttpWebResponse hwresp = (HttpWebResponse)wresp; if(hwresp.StatusCode == HttpStatusCode.OK) { return WebTestResult.STATUS_EXIST; } else { return WebTestResult.STATUS_NOT_EXIST; } } else { return WebTestResult.STATUS_NOT_HTTP; } } catch(WebException wex) { if(wex.Response == null) { return WebTestResult.STATUS_NO_HOST; } else { if(wex.Response is HttpWebResponse) { HttpWebResponse hwresp = (HttpWebResponse)wex.Response; if(hwresp.StatusCode == HttpStatusCode.OK) { throw new SystemException("Should never happen"); } else { return WebTestResult.STATUS_NOT_EXIST; } } else { return WebTestResult.STATUS_NOT_HTTP; } } } } } public class MainClass { public static void Main(string[] args) { Console.WriteLine(WebTest.Exist("http://arne/index.html")); Console.WriteLine(WebTest.Exist("http://arne/notexist.html")); Console.WriteLine(WebTest.Exist("http://notexist/index.html")); } } }