views:

24

answers:

1

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;
        }
    }
    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?

+1  A: 

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.

Hans Passant
thx but there is some errors in my function. Some files have exception "file used by another process". How to know about file is used by other processes or not?
Xaver
@xaver: you are doing something else to the files to get an exception like that. The exception is how you know that the file is in use.
Hans Passant
i do not use that files (that files are located in "C:\WINDOWS\SoftwareDistribution\EventCache\" but they are have not the system or hidden attributes). how i can now that file are in use by some processes?
Xaver
Again: "the exception is how you know that the file is in use."
Hans Passant