C# - Cannot access all files

后端 未结 2 612
名媛妹妹
名媛妹妹 2021-01-14 05:27

My application uses the .NET object Directory.GetFiles()

The actual overload I\'m using is

var allFiles = Directory.GetFiles(\"C:\\\\Use         


        
2条回答
  •  既然无缘
    2021-01-14 06:18

    The directory %AppData% is a system-protected directory. Windows will try to block any access to this directory as soon as the access was not authorized (An access from another user than the Administrator).

    Only the Administrator by default has privileges to read and write from/to this directory.

    Alternatively, you can catch the exception and see if the result is Access Denied. Then, you may prompt the user to run as an Administrator to complete this step. Here's a simple example to prompt the user to run as Administrator

    try
    {
         var allFiles = Directory.GetFiles("C:\\Users\\Dave", "*.*", SearchOption.AllDirectories);
    }
    catch (Exception EX)
    {
         if (EX.Message.ToLower().Contains("is denied."))
         {
              ProcessStartInfo proc = new ProcessStartInfo();
              proc.UseShellExecute = true;
              proc.WorkingDirectory = Environment.CurrentDirectory;
              proc.FileName = Application.ExecutablePath;
              proc.Verb = "runas"; //Required to run as Administrator
              try
              {
    
              Process.Start(proc);
    
              }
              catch
              {
                   //The user refused to authorize
              }
         }
    }
    

    However, you may always prompt the user to authorize when your application launches which is NOT always RECOMMENDED. To do this, you'll have to edit your project app.manifest file

    Locate and change the following line

    
    

    to

    
    

    Thanks,
    I hope you find this helpful :)

提交回复
热议问题