System.Web.Hosting.HostingEnvironment.MapPath returns null in unit test

Possibly save 1 hour of your time: There are times when you need to access a file that is included within your application. This could be a data file. In this case, you may need to grab the path of this file on your server.

You can use System.Web.Hosting.HostingEnvironment.MapPath(“~/yourPath”) but this returns null in your functional unit tests.

An easy way to fix this is to check if it is running in a hosted environment. If it is not, then use AppDomain.CurrentDomain.BaseDirectory.


private static string MapPath(string filePath)
{
var hostingRoot = System.Web.Hosting.HostingEnvironment.IsHosted
? System.Web.Hosting.HostingEnvironment.MapPath("~/")
: AppDomain.CurrentDomain.BaseDirectory;

return Path.Combine(hostingRoot, filePath.Substring(1).Replace('/', '\\'));
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s