Monday, March 24, 2008

Set security access to folder

I'm currently doing a small function, where I need to create folder dynamically, if the folder does not exist.

Creating folder is easy, but I also need to set the security access. Finally, I've found the way of doing this. Happy

I have created a simple class to perform this Directory-related tasks, named "Folder".

Firstly, we need to include System.IO (for Directory class) & System.Security.AccessControl (for FileSystemRights & AccessControlType enums).

public static bool Exists(string folderPath)
{
return Directory.Exists(folderPath);
}

public static void Create(string folderPath)
{
Directory.CreateDirectory(folderPath);
}

public static void Delete(string folderPath)
{
Directory.Delete(folderPath, true);
}

public static void AddSecurity(string folderPath,
string userAccount,
FileSystemRights fileSystemRights,
AccessControlType controlType)
{
DirectoryInfo folderInfo = new DirectoryInfo(folderPath);

DirectorySecurity folderSecurity = folderInfo.GetAccessControl();

folderSecurity.AddAccessRule(
new FileSystemAccessRule(userAccount, fileSystemRights, controlType));

folderInfo.SetAccessControl(folderSecurity);

}

public static void RemoveSecurity(string folderPath,
string userAccount,
FileSystemRights fileSystemRights,
AccessControlType controlType)
{
DirectoryInfo folderInfo = new DirectoryInfo(folderPath);

DirectorySecurity folderSecurity = folderInfo.GetAccessControl();

folderSecurity.RemoveAccessRule(
new FileSystemAccessRule(userAccount, fileSystemRights, controlType));

folderInfo.SetAccessControl(folderSecurity);

}

public static string[] GetListOfFileSystemRights()
{
return Enum.GetNames(typeof(FileSystemRights));
}

public static string[] GetListOfAccessControlTypes()
{
return Enum.GetNames(typeof(AccessControlType));
}



Function: If the folder does not exist, create it and set security access.




if (Folder.Exists(folderPath) == false)
{
Folder.Create(folderPath);
Folder.AddSecurity(folderPath,"MY\\CHONGLK", FileSystemRights.Modify,AccessControlType.Allow);
}



 


To remove the security access for certain rights, use the RemoveSecurity method:



Folder.RemoveSecurity(folderPath,"MY\\CHONGLK", FileSystemRights.Modify,AccessControlType.Allow);



The last two functions is to allow users to bind the list of enum values to the UI control.




//List all FileSystemRights values in dropdownlist
systemRightsDropDownList.DataSource = Folder.GetListOfFileSystemRights();
systemRightsDropDownList.DataBind();

//List all AccessControlTypes values in dropdownlist
controlTypeDropDownList.DataSource = Folder.GetListOfAccessControlTypes();
controlTypeDropDownList.DataBind();



It's quite simple, but I didn't know these methods before this. Tongue At least, I learnt something new.

2 comments:

  1. hi,

    I need to take the records(~30,000) and put into one single file. Kindly let me know how to do this programmatically. Thanks in advance

    ReplyDelete