gpt4 book ai didi

c# - 在计算目录大小时获取 UnauthorizedAccessException

转载 作者:太空宇宙 更新时间:2023-11-03 20:20:12 26 4
gpt4 key购买 nike

我有一个简单的方法来计算目录和其中所有文件的大小。这是代码:

using System;
using System.IO;

namespace MyProject.Libs
{
public sealed class DirectorySize
{
public static long GetDirectorySize(DirectoryInfo dir)
{
long total = 0;

FileInfo[] fileInfos = dir.GetFiles();
foreach (FileInfo fileInfo in fileInfos)
{
total += fileInfo.Length;
}

DirectoryInfo[] dirInfos = dir.GetDirectories();
foreach (DirectoryInfo dirInfo in dirInfos)
{
total += DirectorySize.GetDirectorySize(dirInfo);
}

return total;
}
}
}

当我在驱动器 c:\上使用它时,我收到“UnauthorizedAccessException”和一条消息“访问路径 'C:\Documents and Settings' 被拒绝。”即:

DirectoryInfo di = new DirectoryInfo(Path.GetPathRoot(Environment.SystemDirectory));
long ds = DirectorySize.GetDirectorySize(di);

尝试以管理员身份运行 Visual Studio。全部都一样。为什么?

最佳答案

您的代码在 C:\Documents and Settings 上失败,现在是 junction point指向 C:\Users。您可以使用目录的 FileAttributes.ReparsePoint 进行检查。

这是带有额外异常处理的修改后的代码(对于您未授权的其他目录):

public sealed class DirectorySize
{
public static long GetDirectorySize(DirectoryInfo dir)
{
long total = 0;
FileAttributes attributes = File.GetAttributes(dir.FullName);
if (!((attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint))
{
try{
FileInfo[] fileInfos = dir.GetFiles();
foreach (FileInfo fileInfo in fileInfos)
{
total += fileInfo.Length;
}

DirectoryInfo[] dirInfos = dir.GetDirectories();
foreach (DirectoryInfo dirInfo in dirInfos)
{
total += DirectorySize.GetDirectorySize(dirInfo);
}
} catch (UnauthorizedAccessException)
{
// log this?
}
}

return total;
}
}

Junction Points (Windows)

In Windows Vista and Windows Server 2008, the default locations for user data and system data have changed. For example, user data that was previously stored in the %SystemDrive%\Documents and Settings directory is now stored in the %SystemDrive%\Users directory. For backward compatibility, the old locations have junction points that point to the new locations. For example, C:\Documents and Settings is now a junction point that points to C:\Users. Backup applications must be capable of backing up and restoring junction points. These junction points can be identified as follows: They have the FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_HIDDEN, and FILE_ATTRIBUTE_SYSTEM file attributes set. They also have their access control lists (ACLs) set to deny read access to everyone. Applications that call out a specific path can traverse these junction points if they have the required permissions. However, attempts to enumerate the contents of the junction points will result in failures.

关于c# - 在计算目录大小时获取 UnauthorizedAccessException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14076336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com