Monday, April 18, 2011

How to change the file access permission in C#

Hi, After reading this post you will be able to change the file system rights of a file using C# .net.
//Namespaces required
using System.Security.Principal;
using System.Security.AccessControl;

//code snippet
NTAccount act = new NTAccount("users");//Account name

string fileName ="c:\anyFile";//Target file of which access permission has to modified.

//Create a FileSecurity object
FileSecurity fileSecurity = File.GetAccessControl(fileName);

//Modify the FileSecurity object with full control
fileSecurity.AddAccessRule(new FileSystemAccessRule(act, FileSystemRights.FullControl, AccessControlType.Allow));

//Apply the modified access control
File.SetAccessControl(fileName , fileSecurity);

No comments:

Post a Comment