您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 项目/工程管理 > C#添加文件和文件夹访问权限
其实在.NET中一切的操作和编程变的非常的简单而明了。如想要添加一个文件或文件夹访问用户并为其设置权限的话,如果在C++中实现则非常的复杂。并同时要调用那些烦人的API函数才能完成。但在.NET中则不同,因为.NET中用了很多已封装的类来完成。其实封装类的内部已经封装了系统的API函数从而解决了应用层的编程者。以下是C#实现。用VisualStudio2010编写,在WIN7中测试通过。1、文件staticvoidMain(string[]args){SetAccount(@C:\eee.txt,BATCH);Console.WriteLine(OK);Console.Read();}publicstaticvoidSetAccount(stringfilePath,stringusername){FileInfofileInfo=newFileInfo(filePath);FileSecurityfileSecurity=fileInfo.GetAccessControl();dirsecurity.AddAccessRule(newFileSystemAccessRule(username,FileSystemRights.FullControl,AccessControlType.Allow));//以完全控制为例dirinfo.SetAccessControl(fileSecurity);}2、文件夹publicstaticvoidMain(){SetFolderACL(C:\\test,BATCH,FileSystemRights.FullControl,AccessControlType.Allow);}publicstaticboolSetFolderACL(StringFolderPath,StringUserName,FileSystemRightsRights,AccessControlTypeAllowOrDeny){InheritanceFlagsinherits=InheritanceFlags.ContainerInherit|InheritanceFlags.ObjectInherit;returnSetFolderACL(FolderPath,UserName,Rights,AllowOrDeny,inherits,PropagationFlags.None,AccessControlModification.Add);}publicstaticboolSetFolderACL(StringFolderPath,StringUserName,FileSystemRightsRights,AccessControlTypeAllowOrDeny,InheritanceFlagsInherits,PropagationFlagsPropagateToChildren,AccessControlModificationAddResetOrRemove){boolret;DirectoryInfofolder=newDirectoryInfo(FolderPath);DirectorySecuritydSecurity=folder.GetAccessControl(AccessControlSections.All);FileSystemAccessRuleaccRule=newFileSystemAccessRule(UserName,Rights,Inherits,PropagateToChildren,AllowOrDeny);dSecurity.ModifyAccessRule(AddResetOrRemove,accRule,outret);folder.SetAccessControl(dSecurity);returnret;}
本文标题:C#添加文件和文件夹访问权限
链接地址:https://www.777doc.com/doc-2901511 .html