访问C#中被拒绝的目录 - 控制台应用程序

时间:2016-04-06 21:25:09

标签: c# console-application

我正在尝试访问Documents目录和子目录,但每次都说访问被拒绝。我看到了例外:

  

System.UnauthorizedAccessException:拒绝访问路径'C:\ Users \ MyUser \ Documents \ My Music'

这是我的代码 - 我要做的就是获取此目录的总大小。

class Program
{
      static void Main(string[] args)
      {
          try {
              // Make a reference to a directory.
              string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);              
              DirectoryInfo di = new DirectoryInfo(path);

              // Get a reference to each file in that directory.
              FileInfo[] fiArr = di.GetFiles(".", SearchOption.AllDirectories);

              // Display the names and sizes of the files.
              Console.WriteLine("The directory {0} contains the following files:", di.Name);

              long size = 0;
              foreach (FileInfo f in fiArr)
              {
                  size += f.Length;
                  size++;
              }
              Console.WriteLine("The size of desktop files." + size);
          }
          catch(Exception e)
          {
              Console.WriteLine("Exceptions {0}" , e);
          }         
      }    
}

3 个答案:

答案 0 :(得分:2)

从我可以从略读this thread收集的内容可能是这些文件夹是为Windows向后兼容性提供的软链接。

为了解决编码问题,您可以进行自己的递归文件夹搜索,忽略当前用户无权访问给定文件夹时抛出的异常。

或许这样的事情:

    static IEnumerable<FileInfo> GetAllFilesRecursive(string path)
    {
        var di = new DirectoryInfo(path);
        var files = new List<FileInfo>();
        files.AddRange(di.GetFiles("."));

        foreach (var directory in Directory.GetDirectories(path))
        {
            try
            {
                files.AddRange(GetAllFilesRecursive(directory));
            }
            catch (UnauthorizedAccessException) // ignore directories which the user does not have access to
            {}

        }
        return files;
    }

然后重写您的代码以使用新功能:

    static void Main(string[] args)
    {
        try
        {
            // Make a reference to a directory.
            string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var fiArr = GetAllFilesRecursive(path);

            // Display the names and sizes of the files.
            Console.WriteLine("The directory {0} contains the following files:", path);

            long size = 0;
            foreach (FileInfo f in fiArr)
            {
                size += f.Length;
                size++;
            }
            Console.WriteLine("The size of desktop files." + size);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exceptions {0}", e);
        }
    }  

答案 1 :(得分:1)

搜索应该在TopDirectoryOnly上,而不是在AllDirectories上。

问题出在这一行:

FileInfo[] fiArr = di.GetFiles(".", SearchOption.AllDirectories);

将其更改为:

FileInfo[] fiArr = di.GetFiles(".", SearchOption.TopDirectoryOnly);

这应该有用。

答案 2 :(得分:0)

某些SpecialFolders需要特定的管理员权限才能正常运行。您必须在Admin priviledges中运行您的代码。