我想知道文件夹的大小
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,它也会被拒绝。
如何解决这个问题?
发布于 2017-04-20 17:39:36
我想你不能这样做,命令如下:
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]您可以看到,应用程序数据是指向ProgramData的连接点。Windows包括许多类似的连接点,以便向后兼容较旧的应用程序。
交叉点上的安全权限明确禁止列出文件,这就是为什么您无法获得其内容的列表:
C:\ProgramData>icacls "Application Data" /L
Application Data Everyone:(DENY)(S,RD)
Everyone:(RX)
NT AUTHORITY\SYSTEM:(F)
BUILTIN\Administrators:(F)发布于 2017-04-20 18:57:56
由于某些原因,在文件系统上枚举可能会引发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;
} );https://stackoverflow.com/questions/43515379
复制相似问题