C# - Cannot access all files

谁都会走 提交于 2019-12-02 01:24:06

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

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

to

<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />

Thanks,
I hope you find this helpful :)

It is better to use a foreach loop to get the folder names that you can acces:

DirectoryInfo dI = new DirectoryInfo(@"C:\Users\Dave");
List<string> files = new List<string>();
foreach (DirectoryInfo subDI in dI.GetDirectories())
{
        if ((subDI.Attributes & (FileAttributes.ReparsePoint | FileAttributes.System)) !=
        (FileAttributes)0)
              continue;
        files.Add(subDI.FullName);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!