我想向这个脚本添加一个递归命令,允许它遍历当前的目录子目录/文件,并将子文件夹/文件的权限设置为我想要的任何内容。这是我到目前为止所拥有的,它允许在第一组子目录上更改权限。显然,我可以添加相同的代码以继续深入了解文件夹结构,但并非每个根文件夹中都有相同数量的子文件夹。我想添加递归命令来循环遍历所有子目录,当没有更多子目录时,转到下一个根文件夹。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.AccessControl;
using System.Management;
using System.Management.Instrumentation;
namespace ApplyPermissions
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void selectDirectoryBtn_Click(object sender, EventArgs e)
{
FolderBrowserDialog myFolderBrowserDialog = new FolderBrowserDialog();
myFolderBrowserDialog.ShowDialog();
selectedDirBox.Text = myFolderBrowserDialog.SelectedPath.ToString();
try
{
DirectoryInfo myDirectoryInfo = new DirectoryInfo(selectedDirBox.Text);
foreach (DirectoryInfo currentDir in myDirectoryInfo.GetDirectories())
{
toolStripStatusLabel1.Text = currentDir.Name;
DirectorySecurity DirSecurity = currentDir.GetAccessControl();
DirSecurity.AddAccessRule(new FileSystemAccessRule(“Whatever permissions group I choose”, FileSystemRights.CreateFiles, AccessControlType.Allow));
currentDir.SetAccessControl(DirSecurity);
// Step thru each file within current Directory and assign access
foreach (FileInfo currentFile in currentDir.GetFiles())
{
FileSecurity fileSecurity = currentFile.GetAccessControl();
fileSecurity.AddAccessRule(new FileSystemAccessRule("Whatever permissions group I choose", FileSystemRights.FullControl, AccessControlType.Allow));
currentFile.SetAccessControl(fileSecurity);
}
foreach (DirectoryInfo subDir in currentDir.GetDirectories ())
{
toolStripStatusLabel1.Text = currentDir.Name + "/" + subDir.Name;
DirectorySecurity allsubDirSecurity = subDir.GetAccessControl();
allsubDirSecurity.AddAccessRule(new FileSystemAccessRule("Whatever permissions group I choose ", FileSystemRights.FullControl, AccessControlType.Allow));
subDir.SetAccessControl(allsubDirSecurity);
// Step thru each file within current SubDirectory and assign access
foreach (FileInfo currentFile in subDir.GetFiles())
{
FileSecurity fileSecurity = currentFile.GetAccessControl();
fileSecurity.AddAccessRule(new FileSystemAccessRule("Whatever permissions group I choose", FileSystemRights.FullControl, AccessControlType.Allow));
currentFile.SetAccessControl(fileSecurity);
}
}
}
labelFinished.Text = "Completed Successfully";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "/////////////////" + ex.StackTrace);
}
}
}
}