asp.net 下的访问文件或者文件夹无权限被拒绝

本文介绍了一种解决程序中动态配置文件访问权限的方法,通过设置文件夹权限来避免访问被拒绝的问题,确保程序运行的稳定性和可移植性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我们要访问我程序中部分动态配置文件时程序报错说访问被拒绝

这是因权限不足引起的。当然你也可以手动去为某个文件去添加权限

但是这样的效率以及程序的可移植性就太差了。在下这里提供了一个方法设置文件夹net 下的权限

一般是在文件夹或者是文件不存在时创建文件或文件夹后使用这个方法  

private void SetRight(string folderpath)
        {
          bool result=false;
            DirectoryInfo folder=new DirectoryInfo(folderpath);
            folder.Attributes|=FileAttributes.Normal;
            folder.Attributes&=~FileAttributes.Hidden; // remove the folder Hidden attribute
            folder.Attributes&=~FileAttributes.ReadOnly;// remove the folder ReadOnly attribute
            DirectorySecurity foldersecurity = new DirectorySecurity();
            FileSystemAccessRule filerule = new FileSystemAccessRule("INTERACTIVE",FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);
            FileSystemAccessRule filerule1=new FileSystemAccessRule("NETWORK SERVICE",FileSystemRights.FullControl,InheritanceFlags.ContainerInherit,PropagationFlags.InheritOnly, AccessControlType.Allow);
            FileSystemAccessRule filerule2=new FileSystemAccessRule("NETWORK",FileSystemRights.FullControl,InheritanceFlags.ContainerInherit,PropagationFlags.InheritOnly, AccessControlType.Allow);
            foldersecurity.ModifyAccessRule(AccessControlModification.Add, filerule, out result);    
            foldersecurity.ModifyAccessRule(AccessControlModification.Add,filerule1,out result);
            foldersecurity.ModifyAccessRule(AccessControlModification.Add,filerule2,out result); 
            folder.SetAccessControl(foldersecurity);
        }

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值