如何在Windows中从C#程序更改文件权限?

时间:2012-07-14 13:47:42

标签: c# file-permissions directory-permissions

我制作了一个C#windows应用程序,它将在C盘中搜索该文件夹 用户在文本框中输入,搜索将在用户按下按钮后开始。 问题是我得到一个例外告诉我:

Access To The Path 'C:\Documents and Settings' is Denied

如何找到我无法访问的C驱动器(或任何其他驱动器)中的任何文件夹/文件,并通过我的C#程序更改其权限以访问已授予的权限,以便我可以继续搜索?

在Linux中有chmod,但我不知道windows ..请帮助:)

搜索代码:

string operationSucceeded = "Operation Completed Successfully";
Exception NoFilesFound = new Exception("No File(s) Found In Specified Directory");
List<string> foundFolders = new List<string>();

private void button5_Click(object sender, EventArgs e)
{
  try
  {
    Search_In_For("C:\\", WantedFile_Folder_TextBox.Text);
    if (foundFolders == null) throw NoFilesFound;
    for (int i = 0; i < foundFolders.Count; i++)
    SearchResultsTextBox.Text += (foundFolders[i] + "\n");
    MessageBox.Show(operationSucceeded);
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

delegate void SearchDelegate(string searchDir, string wanted);

private void Search_In_For(string searchDir, string wanted)
{
  string[] foldersInThisDir = Directory.GetDirectories(searchDir);
  if (foldersInThisDir.Length == 0) return;
  for (int i = 0; i < foldersInThisDir.Length; i++)
    if (foldersInThisDir[i].Contains(wanted))
      foundFolders.Add(foldersInThisDir[i]);
  SearchDelegate sd = new SearchDelegate(Search_In_For);
  for (int i = 0; i < foldersInThisDir.Length; i++)
    sd(foldersInThisDir[i] , wanted);
}

1 个答案:

答案 0 :(得分:0)

尝试从Windows资源管理器中以“管理员”身份运行程序。