C#创建文件夹并设置权限
Posted 与时俱进
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#创建文件夹并设置权限相关的知识,希望对你有一定的参考价值。
/*
需要添加以下命名空间:
using System.IO;
using System.Security.AccessControl;
*/
string sPath = Server.MapPath(文件夹名称字符串);
Directory.CreateDirectory(sPath);
addpathPower(sPath, "ASPNET", "FullControl");
//////////////////////////////////////////////////
public void addpathPower(string pathname, string username, string power)
{
DirectoryInfo dirinfo = new DirectoryInfo(pathname);
if ((dirinfo.Attributes & FileAttributes.ReadOnly) != 0)
{
dirinfo.Attributes = FileAttributes.Normal;
}
//取得访问控制列表
DirectorySecurity dirsecurity = dirinfo.GetAccessControl();
switch (power)
{
case "FullControl":
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
break;
case "ReadOnly":
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Read, AccessControlType.Allow));
break;
case "Write":
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Write, AccessControlType.Allow));
break;
case "Modify":
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Modify, AccessControlType.Allow));
break;
}
dirinfo.SetAccessControl(dirsecurity);
}
需要添加以下命名空间:
using System.IO;
using System.Security.AccessControl;
*/
string sPath = Server.MapPath(文件夹名称字符串);
Directory.CreateDirectory(sPath);
addpathPower(sPath, "ASPNET", "FullControl");
//////////////////////////////////////////////////
public void addpathPower(string pathname, string username, string power)
{
DirectoryInfo dirinfo = new DirectoryInfo(pathname);
if ((dirinfo.Attributes & FileAttributes.ReadOnly) != 0)
{
dirinfo.Attributes = FileAttributes.Normal;
}
//取得访问控制列表
DirectorySecurity dirsecurity = dirinfo.GetAccessControl();
switch (power)
{
case "FullControl":
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
break;
case "ReadOnly":
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Read, AccessControlType.Allow));
break;
case "Write":
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Write, AccessControlType.Allow));
break;
case "Modify":
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Modify, AccessControlType.Allow));
break;
}
dirinfo.SetAccessControl(dirsecurity);
}
以上是关于C#创建文件夹并设置权限的主要内容,如果未能解决你的问题,请参考以下文章
以编程方式检索源文件夹列表并创建一个(如果不存在) - C# + VSTS 2017