[.net] ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

What is the correct way to find the absolute path to the App_Data folder from a Controller in an ASP.NET MVC project? I'd like to be able to temporarily work with an .xml file and I don't want to hardcode the path.

This does not work:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        string path = VirtualPathUtility.ToAbsolute("~/App_Data/somedata.xml");

        //.... do whatever 

        return View();
    }

}

I think outside of the web context VirtualPathUtility.ToAbsolute() doesn't work. string path comes back as "C:\App_Data\somedata.xml"

Where should I determine the path of the .xml file in an MVC app? global.asax and stick it an application-level variable?

This question is related to .net asp.net-mvc absolute-path

The answer is


string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();

This is probably a more "correct" way of getting it.


string Index = i;
            string FileName = "Mutton" + Index + ".xml";
            XmlDocument xmlDoc = new XmlDocument();

            var path = Path.Combine(Server.MapPath("~/Content/FilesXML"), FileName);
            xmlDoc.Load(path); // Can use xmlDoc.LoadXml(YourString);

this is the best Solution to get the path what is exactly need for now


The most correct way is to use HttpContext.Current.Server.MapPath("~/App_Data");. This means you can only retrieve the path from a method where the HttpContext is available. It makes sense: the App_Data directory is a web project folder structure [1].

If you need the path to ~/App_Data from a class where you don't have access to the HttpContext you can always inject a provider interface using your IoC container:

public interface IAppDataPathProvider
{
    string GetAppDataPath();
}

Implement it using your HttpApplication:

public class AppDataPathProvider : IAppDataPathProvider
{
    public string GetAppDataPath()
    {
        return MyHttpApplication.GetAppDataPath();
    }
}

Where MyHttpApplication.GetAppDataPath looks like:

public class MyHttpApplication : HttpApplication
{
    // of course you can fetch&store the value at Application_Start
    public static string GetAppDataPath()
    {
        return HttpContext.Current.Server.MapPath("~/App_Data");
    }
}

[1] http://msdn.microsoft.com/en-us/library/ex526337%28v=vs.100%29.aspx


Phil Haak has an example that I think is a bit more stable when dealing with paths with crazy "\" style directory separators. It also safely handles path concatenation. It comes for free in System.IO

var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);

However, you could also try "AppDomain.CurrentDomain.BaseDirector" instead of "Server.MapPath".


I try to get in the habit of using HostingEnvironment instead of Server as it works within the context of WCF services too.

 HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml");

string filePath = HttpContext.Current.Server.MapPath("~/folderName/filename.extension");

OR

string filePath = HttpContext.Server.MapPath("~/folderName/filename.extension");

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to absolute-path

Server Document Root Path in PHP Do I need to pass the full path of a file in another directory to open()? PHP absolute path to root How to use relative/absolute paths in css URLs? src absolute path problem Relative path to absolute path in C#? Get filename and path from URI from mediastore Convert absolute path into relative path given a current directory using Bash How to get the file-path of the currently executing javascript code Resolve absolute path from relative path and/or file name