← All articles
development

Finding App_Data Programmatically

Server.MapPath breaks in unit tests. Here's the AppDomain.CurrentDomain.GetData trick to find your ASP.NET MVC App_Data path anywhere.

Donn Felker

Donn Felker

2009.04.14 · 1 min read · updated July 5, 2013

While writing some code I needed to be able to access the the App_Data directory in my ASPNET MVC app. Doing this usually involves a Server.MapPath, but this wont work for my unit test.

Here’s how you can get around it:

var appDataPath = (string)AppDomain.CurrentDomain.GetData(“DataDirectory”) ?? AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

Now I have my data directory for the test as well as during execution of the ASPNET MVC app.

During unit test execution it will be in testing directory while at runtime it will be in the ASPNET App_Data directory.

Donn Felker

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading