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;}

1 / 2
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功