我希望获得文件夹的大小
C:\ProgramData\
我使用以下代码
public static long GetDirectorySize(string folderPath)
{
DirectoryInfo di = new DirectoryInfo(folderPath);
return di.EnumerateFiles("*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}
但它提示我错误:
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access to the path 'C:\ProgramData\Application Data' is denied.
我已经设置了
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
在app.manifest中。似乎即使我直接在Windows中打开C:\ ProgramData \ Application Data它也被拒绝。
如何解决此问题?
答案 0 :(得分:0)
我想你不能这样做,从命令如下:
C:\ProgramData>dir /a
Volume in drive C is OSDisk
Volume Serial Number is 067E-828E
Directory of C:\ProgramData
04/20/2017 02:00 PM <DIR> .
04/20/2017 02:00 PM <DIR> ..
07/14/2009 01:08 PM <JUNCTION> Application Data [C:\ProgramData]
您可以看到,Application Data是一个指向ProgramData的连接点。 Windows包含许多类似的连接点,以便与旧应用程序向后兼容。
联结点上的安全权限明确禁止列出文件,这就是为什么你无法获得其内容列表的原因:
C:\ProgramData>icacls "Application Data" /L
Application Data Everyone:(DENY)(S,RD)
Everyone:(RX)
NT AUTHORITY\SYSTEM:(F)
BUILTIN\Administrators:(F)
答案 1 :(得分:0)
由于某些原因,枚举文件系统可能会引发SecurityException
。
最佳选择是对这些例外进行回调。
public class FileSytemInfoErrorArgs
{
public FileSytemInfoErrorArgs( FileSystemInfo fileSystemInfo, Exception error )
{
FileSystemInfo = fileSystemInfo;
Error = error;
}
public FileSystemInfo FileSystemInfo { get; }
public Exception Error { get; }
public bool Handled { get; set; }
}
public static class DirectoryInfoExtensions
{
public static long GetTotalSize( this DirectoryInfo di, Action<FileSytemInfoErrorArgs> errorAction = null )
{
long size = 0;
foreach ( var item in di.EnumerateFileSystemInfos() )
{
try
{
size += ( item as FileInfo )?.Length
?? ( item as DirectoryInfo )?.GetTotalSize( errorAction )
?? throw new InvalidOperationException();
}
catch ( Exception ex )
{
var arg = new FileSytemInfoErrorArgs( item, ex );
errorAction?.Invoke( arg );
if ( !arg.Handled )
{
throw;
}
}
}
return size;
}
}
最后
var path = Environment.GetFolderPath( Environment.SpecialFolder.CommonApplicationData );
var dir = new DirectoryInfo( path );
var totalSize = dir.GetTotalSize(
errorAction: e =>
{
// Console.WriteLine( "{0}: {1}", e.FileSystemInfo.FullName, e.Error.Message );
e.Handled = true;
} );