您的位置:首页 > 编程语言 > C#

C# 设置文件夹访问权限

2012-03-27 21:59 323 查看

Applyingpermissionsonfolders/directoriesinWindowsisoneofthethingsdeveloperswanttocontrolwiththeirapplications.TodaywearegoingtolookathowcanwecreatesuchanapplicationinC#whichcandefineanykindof
permissiontoanyuseraccountinWindowsenvironment.

StartVisualStudioandcreateanewC#Windowsapplication.NameitDirectoryPermissionandCreateaninterfacewhichlookssimilartotheonebelow:

1.ChangethetextofyourwindowtoFolderPermissionoranyotheryoulike.

2.Dragtwolabels,twobuttons,1textboxand1comboboxontheform.NamethebuttonsasSelectDirectorybtnandPermissionbtnandleavethenamesofothersasdefault.

3.Nowweneedtoaddtworeferences,forthatright-clickyourprojectrootandselectAddreference.

4.FromtheAddReferenceMenu,addfollowingtwohighlightedreferences.

BothofthesereferencesactuallyhelpusinteractwithOperatingSystem’saccountmanagementandqueries.

5.RightclickonyourWindowsFormandSelectViewCode.

6.FirstofallwewilldefinethereferencesthatweaddedinStep4.We’llalsoaddSystem.IOandSystem.Security.AccessControl

1:usingSystem.IO;

2:usingSystem.Security.AccessControl;

3:usingSystem.Management;

4:usingSystem.Management.Instrumentation;



7.Nowwearegoingtodefineamethodwhichwillfillourcomboboxwithnamesofalluseraccount.

1:publicvoidGetUsers()

2:{

3://ThisquerywillqueryforalluseraccountnamesinourcurrentDomain

4:SelectQuerysQuery=newSelectQuery("Win32_UserAccount","Domain='"+System.Environment.UserDomainName.ToString()+"'");

5:

6:try

7:{

8://SearchingforavailableUsers

9:ManagementObjectSearchermSearcher=newManagementObjectSearcher(sQuery);

10:

11:foreach(ManagementObjectmObjectinmSearcher.Get())

12:{

13://Addingallusernamesinourcombobox

14:comboBox1.Items.Add(mObject["Name"]);

15:}

16:}

17:catch(Exceptionex)

18:{

19:MessageBox.Show(ex.ToString());

20:}

21:}

Note:System.Environment.UserDomainNameisgoingtodeliverusourcurrentdomain.



8.Inordertomaketheabovemethodeffective,weneedtomodifyourformconstructor.

1:publicForm1()

2:{

3:InitializeComponent();

4:GetUsers();

5:}



9.Nowwe’llgobacktoourdesignwindowanddoubleclickSelectDirectorybuttontodefineitsclickingevent.Changethedefinitiontofollowing;

1:privatevoidSelectDirectorybtn_Click(objectsender,EventArgse)

2:{

3://creatinganewinstancefotFolderBrowsingDialogtoprovideusercapabilitytoselecttargetFolder

4:FolderBrowserDialogmyFolderBrowserDialog=newFolderBrowserDialog();

5:

6://showingdialog

7:myFolderBrowserDialog.ShowDialog();

8:

9://ShowthepathofselecteddirectoryinourtextBox

10:textBox1.TextmyFolderBrowserDialog.SelectedPath.ToString();

11:}



10.MovebacktoyourdesignviewandaddaClickeventtothesecondbuttoni.e.MakeUnreadable,doubleclickittomodifytheevent.

1:privatevoidPermissionbtn_Click(objectsender,EventArgse)

2:{

3://retrievingthedirectoryinformation

4:DirectoryInfomyDirectoryInfo=newDirectoryInfo(textBox1.Text);

5:

6://GetaDirectorySecurityobjectthatrepresentsthe

7://currentsecuritysettings.

8:DirectorySecuritymyDirectorySecurity=myDirectoryInfo.GetAccessControl();

9:stringUser=System.Environment.UserDomainName+"\\"+comboBox1.SelectedItem.ToString();

10:

11://AddtheFileSystemAccessRuletothesecuritysettings.

//FileSystemRightsisabiglistwearecurrentusingReadpropertybutyou

//canalteranyotherormanysmeofwhichare:

12://CreateDirectories:forsubdirectoriesAuthority

13://CreateFiles:forfilescreationaccessinaparticularfolder

14://Delete:fordeletionathorityonfolder

15://DeleteSubdirectoriesandfiles:forauthorityofdeletionover

//subdirectoriesandfiles

16://Executefile:Forexecutionaccessibilityinfolder

17://Modify:Forfoldermodification

18://Read:Fordirectoryopening

19://Write:toaddthingsindirectory

20://FullControl:Foradministrationrightsetcetc

21:

22://AlsoAccessControlTypewhichareoftwokindseither“Allow”or“Deny”

23:myDirectorySecurity.AddAccessRule(newFileSystemAccessRule(User,FileSystemRights.Read,AccessControlType.Deny));

24:

25://Setthenewaccesssettings.

26:myDirectoryInfo.SetAccessControl(myDirectorySecurity);

27:

28://ShowingaSuccesfullyDoneMessage

29:MessageBox.Show("PermissionsAlteredSuccessfully");

30:}


That’sit.Compileandexecutetheapplicationtotestresults.Ifyouhaveanyqueriesfeelfreetoask…Cheers!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: