2/27/2008

ASP.NET "App_Data": Writing files vs Application Restarts

Most ASP.NET developers know that if you create a new file , modify any file in the application root or the /bin folder, or modify web.config, this will trigger an application restart. InProc Session, Application and Cache state go bye-bye. This is a major cause of "WTF" type newsgroup and forum posts by n00b developers who don't yet fully understand the ASP.NET runtime model and its rather complicated set of behaviors - which are by design.

However, there is a special folder, APP_DATA, that is designed not to respond to this filesystemwatcher behavior. In a WebSite application this folder is created by default. It is normally used for SQL Server MDF database files using the UserInstance SQLEXPRESS hosting mechanism, or for XML files.

The good thing to know is that this works the same way (filesystemwatcher events are ignored by the ASP.NET runtime) for Web Application Projects. The only difference is that with a WAP you need to create the folder manually (except with VS 2008, which does create it):

Right - Click the project node in Solution Explorer, choose "Add" from the context menu, and "Add Asp.Net Folder", and choose "App_Data".

You now have the same App_Data folder that would be created by default via a Web Site Project, and it will behave exactly the same. You can put Sql Server MDF files there, use the "User Instance" feature of SQLEXPRESS, and you can write files into this folder or subfolders and they will not cause the ASP.NET runtime to recycle your application when it is in operation.

If you have a site where dynamically generated content files need to be deposited into the file system within the IIS Application root without causing your IIS Application to recycle, this is the way to do it.