ASP.NET MVC 4 Access to the path App_Data is denied

Nick Reeve picture Nick Reeve · Apr 9, 2014 · Viewed 7.6k times · Source

I have been getting the following error after publishing my site:

System.UnauthorizedAccessExceptionAccess to the path 'C:\inetpub\MySite\App_Data' is denied.

Turns out it's because it can't access App_Data\ASPNETDB.MDF. This is because it doesn't exist as my site doesn't use it. I checked my local machine and there is an App_Data folder with the database in but it isn't included in my build in VS. If I delete it however, it is recreated when I run the site in VS.

The site works fine after that once the error seems to clear itself but it happens every time I deploy.

There is no reference to it anywhere in code. How/Why is it getting created on application start and how do I stop it?

I am using SimpleMembership with all data stored in a SQL Server DB.

Answer

Masoud Ghaffari picture Masoud Ghaffari · May 25, 2015

I had this problem before. when you want to publish your App, if the app_data folder was empty, it doesn't copy to the published one. so before publishing, copy a file to app_data folder, then publish your app... or you can check for exist to create inside the code:

var folder = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/");
if (!Directory.Exists(folder)) 
    Directory.CreateDirectory(folder);