In my library I use HostingEnvironment.MapPath for my web application. But I need to call the same function from a windows forms and a windows service.
In Windows application HostingEnvironment.ApplicationID is null, in Web application HostingEnvironment.ApplicationID is something like "99xxx999".
Can I use "HostingEnvironment" to determine if it is Web or Win?
Is it safe to use this?
if (HostingEnvironment.ApplicationID == null)
{
//called from windows application
}
else
{
//called from web application
}
A more standard way to do this it to use the HttpContext.Current method:
if (HttpContext.Current == null)
{
// called from windows application
}
else
{
// called from web application
}
Of course using HttpContext related stuff in non-HTTP related layers of your application is a design smell. It not only smells => it stinks.
A more standard way is to have your code be passed as argument directly the filename as argument. When called from within a web application you would pass Server.MapPath("~/foo.txt")
and when you call it from within a Windows Application you would directly pass the file name relative to the current executable.
This way your code doesn't need to depend on any HTTP specific stuff and can be happily reused in any platform. It is the responsibility of the caller to pass it the filename that your code needs to process. The way this filename is determined is platform specific. Not your code responsibility. Don't mix responsibilities.
Read the msdn documentation here: http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.applicationid(v=vs.100).aspx
It states:
"The application must be running with AspNetHostingPermissionLevel set to high trust to access the ApplicationId property"
I hope you've got your answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With