简体   繁体   中英

How To Change File Permissions In Windows From A C# Program?

I made a C# windows App program that will search In the C drive for the folder that the user enters in a text box, the search will begin after the user presses a button. The problem is that I'm getting an exception telling me:

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

How can I spot any folder/file in the C drive (or any other drive)that I don't have Access to, and change its permission via my C# program to access granted or something, so that I could continue my search ?

In Linux there is chmod, but I don't know about windows .. Please Help :)

The Search Code:

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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM