There are couple of folders that have a special meaning in ASP.NET. Those folders include folders like App_Code where you usually put your code or App_Themes where you put themes. There is also an App_Data folder which "Contains application data files including MDF files, XML files, as well as other data store files" (MSDN).
From App_Data folder description it is obvious that it is where you should put your data. But how to do it? I have searched high and low for a methods or properties that help interact with this directory. The reason is because I don't like hard-coding strings in my code and I would have to hard-code at least one: "~/App_Data". I thought that since there are method to get the location of temp directory:
Or even to get the system direcotry:
There should be a way to get the App_Data directory.
Apparently I was wrong. Unfortunately. There is no Strongly Typed method or property to get to the location of App_Data directory!
I have found 2 places in code where "App_Data" appears as a string (that's why I'm pretty sure there are no properties or methods). One place is a GetDataDirectory method in an internal System.Web.DataAccess.SqlConnectionHelper class and the other is in a SetUpDataDirectory method in a System.Web.HttpRuntime class.
My guess is that the first one is used for Membership Provider that by default uses Microsoft SQL Express database and App_Data directory to store the mdf files. The other one is probably not used at all - I have found no code that calls that method!
When I have looked inside those methods I have found one thing that they have in common. Both set some data object in an AppDomain via:
So I have made a test and used on one of my pages:
string dataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory") as string;
And of course it worked as expected. Unfortunately we cannot (or should not) use this kind of code since it is a dirty hack that relies on internal implementation of some internal classes and it also requires us to hard-code a string. So what's the benefit? The only one is that now I'm pretty sure, that there is no way to interact with App_Data folder using BCL so I will no longer have to search for it on the Internet - thing that I have done countless times.