i want to create functions what get the folder size. I write small function:
private: unsigned long long GetDirectorySize(String^ path) {
unsigned long long size = 0;
DirectoryInfo^ diBase = gcnew DirectoryInfo(path);
if (!diBase->Exists) return 0;
array <FileInfo^>^ files;
array <FileSystemInfo^>^ files2;
try {
files = diBase->GetFiles("*", SearchOption::TopDirectoryOnly);
for each(FileInfo^ file in files) {
size += file->Length;
}
}
开发者_JAVA技巧 return size;
}
But sometimes function return exception. it is DirectoryNotFoundException and UnauthorizedAccessException i want to rewrite this function.that would function just missed a file or folder that caused this exception. How do this?
DirectoryNotFoundException is a bug in your code, you are doing something wrong with the path you pass. UnauthorizedAccessException is common enough, some directories you cannot read, not even with administrator privileges. c:\system volume information is an example, it stores restore point data, hidden from everyone.
Pay attention to DirectoryInfo.Attributes. Avoid recursing into any directory that has the System and Hidden attributes. That will avoid the vast majority of security exceptions. The rest requires GetAccessControl() to check the ACL and verify that the user has read access. The quick fix for awkward code like that is catching the exception.
精彩评论