简体   繁体   中英

Authenticating user to create directory in c#

I've been trying to get around a unauthorizedaccessexception caused by trying to create a folder on an external machine, which resides on the same network, I've tried working around this by adding an accessrule, which doesn't help I still get the same error.

String thepath = @"\\WONEATEMPMACHINE\C\ExampleData\"
DirectoryInfo dInfo = new DirectoryInfo(thepath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();

dSecurity.AddAccessRule(new FileSystemAccessRule("DOMAINEXAMPLE\\wonea",
                        FileSystemRights.Write,
                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                        PropagationFlags.None,
                        AccessControlType.Allow));

                        dInfo.SetAccessControl(dSecurity);

Directory.CreateDirectory(thepath + "\\newfolder");

A quick guess would be that the account that your application is running under needs to have write permission to make such a change to the directory in the first place.

If the account (impersonted or a dedicated application account) doesn't have permission to create within the path specified, it probably doesn't have permission to change the access rules on that path either.

There are probably a few ways to fix this, but the basic goal is that the account the application is running under needs to have write permission on the parent directory at the time of creating the sub-directory.

If your application is impersonating users, one solution is to put those users in a group that already has permission. Alternatively, and maybe a more secure approach, is that the application could switch to a single application account that already has permission to create the directories, assign access to the new directory only to the logged in user, then switch back to the logged in user account. Another option, probably the most secure, is to just create the directories ahead of time, but I'm guessing that those won't all be known ahead of time.

If the application isn't impersonating users, give the application account access before the application runs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM