c#中为文件夹设置权限

在文件操作中,常常会遇到 对所访问的文件夹没有权限 的错误,下面介绍C#中怎么设置文件夹的权限:
 
 1ExpandedBlockStart.gifContractedBlock.gif/**//// <summary>
 2InBlock.gif        /// 为创建的临时文件分配权限
 3InBlock.gif        /// </summary>
 4InBlock.gif        /// <param name="pathname"></param>
 5InBlock.gif        /// <param name="username"></param>
 6InBlock.gif        /// <param name="power"></param>
 7ExpandedBlockEnd.gif        /// <remarks>SKY 2007-8-6</remarks>

 8None.gif        public void addpathPower(string pathname, string username, string power)
 9ExpandedBlockStart.gifContractedBlock.gif        dot.gif{
10InBlock.gif
11InBlock.gif            DirectoryInfo dirinfo = new DirectoryInfo(pathname);
12InBlock.gif
13InBlock.gif            if ((dirinfo.Attributes & FileAttributes.ReadOnly) != 0)
14ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
15InBlock.gif                dirinfo.Attributes = FileAttributes.Normal;
16ExpandedSubBlockEnd.gif            }

17InBlock.gif
18InBlock.gif            //取得访问控制列表
19InBlock.gif            DirectorySecurity dirsecurity = dirinfo.GetAccessControl();
20InBlock.gif
21InBlock.gif            switch (power)
22ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
23InBlock.gif                case "FullControl":
24InBlock.gif                    dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
25InBlock.gif                    break;
26InBlock.gif                case "ReadOnly":
27InBlock.gif                    dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Read, AccessControlType.Allow));
28InBlock.gif                    break;
29InBlock.gif                case "Write":
30InBlock.gif                    dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Write, AccessControlType.Allow));
31InBlock.gif                    break;
32InBlock.gif                case "Modify":
33InBlock.gif                    dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Modify, AccessControlType.Allow));
34InBlock.gif                    break;
35ExpandedSubBlockEnd.gif            }

36ExpandedBlockEnd.gif        }

DirectoryInfo是需要实例化的,而且实例化的时候必须指定文件夹路径,Directory则是静态类.

主程序中调用的写法:
1None.gifprivate void CreateDirectory()
2ExpandedBlockStart.gifContractedBlock.gifdot.gif{
3InBlock.gif   dot.gif
4InBlock.gif   addpathPower(sPath, "ASPNET""FullControl");
5InBlock.gif   dot.gif
6ExpandedBlockEnd.gif}
   一般来说 Username 选用 ASPNET

转载于:https://www.cnblogs.com/leosky2008/archive/2007/08/08/847405.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值