How to set folder permission using C# code?

Not every system has the right folder permission set to all user account and hence, sometime we need special access to specific folder during installation or while executing the application. It is not possible to manually set it up by browsing the folder and hence an automation is mandatory.


If you are looking for a way to set the right permission to specific folder(s) using C# code, this post will help you. Continue reading to learn more about it and grab the code.


How to set folder permission using C# code? (


If you want to set folder permission programmatically, before going further you should first collect couple of data. First one is the complete folder path, the identity of the access rule for which you want to set the permission, the file system rights (read, write, full control etc.), whether you want to inherit folder permission.


Once you are ready with all these details, get the handle of the directory by creating an object of DirectoryInfo, passing the complete folder path. While setting the correct file system access rule, set the user identity under which you want to set the special permission along with other details like read/write/fullControl access etc.


Below is the code snippet that you can refer and modify accordingly as per your business need:


public static void SetFolderPermission(string folderPath)
    var directoryInfo = new DirectoryInfo(folderPath);
    var directorySecurity = directoryInfo.GetAccessControl();
    var currentUserIdentity = WindowsIdentity.GetCurrent();
    var fileSystemRule = new FileSystemAccessRule(currentUserIdentity.Name, 
                                                  InheritanceFlags.ObjectInherit |


I hope, this will be helpful for you in case you are looking for an automated way to set specific folder permission to specific user by using C# code. You can further study it’s different parameters and fine tune it as per your requirement. Let me know, if you need further details on it. I will be happy to help you.


If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter , Facebook , Google+ and LinkedIn . I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.


© 2008-2016 - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top