当我们要访问我程序中部分动态配置文件时程序报错说访问被拒绝
这是因权限不足引起的。当然你也可以手动去为某个文件去添加权限
但是这样的效率以及程序的可移植性就太差了。在下这里提供了一个方法设置文件夹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);
}