If I have a relative path that I need to get from the current server. The following does not work because it is not a valid URI.
var request = WebRequest.Create("\path_to_resource")
I believe that the easiest way would be to put the path in the web.config, however this is easily broken by forgetting to update the config when the application is moved to another server. Is there a better way than?
var request = WebRequest.Create(ConfigurationManager.AppSettings["root"] + "\path_to_resource");
Well, you can always use something like:
Using these various Request object properties will give you your current domain name onto which you can append your sub-folders for your resource.
Request.Url.Schemeis thehttp / httpspart of the URL,System.Uri.SchemeDelimiteris the://part, and theRequest.Url.Hostwill be your actual host name (ie.example.com).If your site is running on a non-standard port, the calls to
Request.Url.Portwill add that into the URL “domain name” also.Note that this is not bullet-proof code, as it assumes your (for example) running SSL (https) on the default port of 443
If you need actual physical file paths, you can use Server.MapPath to retrieve the physical file path of the “root” of your ASP.NET application, and append your sub-folders from there.
See also: ASP.NET Web Site Paths