In some situations, an ASP.NET application might have the need to create or edit a local filefor example, a configuration file. Lets consider the following simple code that opens a file for writing:
<%@ Page Language="C#" %> <%@ Import Namespace="System.IO" %> <script runat="server"> void Page_Load(object sender, EventArgs e) { StreamWriter file = new StreamWriter(serverFile); : file.Close(); } </script>
If you run this or similar code, an unauthorized access exception will normally be thrown.
The ASPNET account has limited privileges and is not authorized to access the requested resource. Avoiding the exception is simple. The only action to take is adding the ASPNET account to the list of accounts that have full control on the specific file or folder. In more technical terms, this action is defined as adding or editing an appropriately configured access control list (ACL) on the file or folder.
If your application manages a well-known and constant number of files, you can deploy them with the needed security settings already in place. If the number and the names of the files being created is not known in advance, you could create a subdirectory, manage to put all the editable files there, and grant ASPNET write permissions on the folder.
But why cant ASP.NET applications create local files? By default, ASP.NET does not impersonate any user, and as a result, all local resources are accessed using the ASP.NET process identitythe ASPNET account on systems prior to Windows 2003 Server, and NetworkService on Windows 2003 Server. In light of this, Windows resources must have an ACL that grants access to the ASP.NET process account. When this is not the case, an access denied exception is generated. Thats why you dont have to modify security configuration to work around the issue; you simply enable the ASP.NET account to work in writing mode on the necessary resources.
Writing to Access .mdb files can often be problematic from within ASP.NET applications. The reason is always related to the fact that the default ASPNET account might not have sufficient permissions to connect to, or write to, an Access database. An Access database is treated as a standalone file; from this standpoint, an .mdb database is in no way different from a plain text file. To work around the issue, you should grant read and write permissions to the ASPNET account to work on the database file. Finally, notice that the error message you get is different when you are trying to connect (without Read permissions) or write (without Write permissions).
Dino Esposito is Wintellect's ADO.NET and XML expert, and a trainer and consultant
based in Rome, Italy. Dino is a contributing editor to Windows Developer
Network and MSDN Magazine, and the author of several books for Microsoft
Press including Building Web Solutions with ASP.NET and ADO.NET
and Applied XML Programming for .NET. Contact Dino at [email protected].