views:

527

answers:

2

I have a windows forms application which serves as a sort of administrative module for an ASP.NET web application. The web application serves multiple countries, and folders are created when new countries are added to the application data.

Unfortunately on the newly added countries I run into an exception with the web application when I go and try to write files in the folders:

System.UnauthorizedAccessException: Access to the path 'C:\...' is denied.

With the web application using ASP.NET impersonation, it's obvious that the default IIS user (MACHINENAME\IUSR_MACHINENAME) has no permissions to write into the folder.

How do I grant permission the the default IIS user upon folder creation?

I understand that

System.IO.Directory.CreateDirectory(string path, DirectorySecurity directorySecurity)

should do this, but I don't understand how to specify the log on name on the DirectorySecurity object.

+2  A: 

Grant permission to create directories and files (read/write/modify/...) to the worker process group (sysname\iis_wpg) to the parent directory of where you want to create the new directories. Make sure that you've set the permissions to apply to this folder, subfolders, and files, then the permissions will be inherited for new folders you create and you won't need to apply them specifically. Rather than doing this for all of App_Data, I'd suggest creating a specific subdirectory and only granting permissions on that subdirectory. If you have multiple apps running on the box you might want to create a new user for the app to run as, change the id of the worker process group, and grant only permission to that specific user.

tvanfosson
A: 

This is the solution I used eventually:

        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
            DirectoryInfo info = new DirectoryInfo(path);
            DirectorySecurity security = info.GetAccessControl();

            security.AddAccessRule(new FileSystemAccessRule(logonName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
            security.AddAccessRule(new FileSystemAccessRule(logonName, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));

            info.SetAccessControl(security); 
        }
Jon Limjap
This is not a great solution, as the directory initially has only default permissions, which are then replaced. In principle, it is possible to hijack the directory by changing its owner to lock the original creator out. For an example of how to specify DirectorySecurity as part of the CreateSubDirectory, see http://stackoverflow.com/questions/1532014/file-permissions-do-not-inherit-directory-permissions
Steven Sudit