Joe Johnston
Joe Johnston

Reputation: 2936

System.UnauthorizedAccessException C# in winforms

The issue is System.UnauthorizedAccessException on recycle bin or documents and settings folders/files. (VS2010 .NET 4.0 C#)

The following LINQ code to query directory sizes. I have tried GetFiles and EnumerateFiles. I am definitely running as admin. In the commented code you can see I tried testing for some attributes from another Stack post without success.

DirectorySize(new DirectoryInfo(@"C:\\"),true);

public static long DirectorySize(DirectoryInfo dInfo, bool includeSubDir)
{
    // Enumerate all the files
    long totalSize = dInfo.EnumerateFiles().Sum(file => file.Length);
        //.Where(d => (d.Attributes & FileAttributes.ReparsePoint) == 0 && (d.Attributes & FileAttributes.System) == 0)
        //.Sum(file => file.Length);

    if (includeSubDir) // Subdirs?
    {
        // Enumerate all sub-directories
        totalSize += dInfo.EnumerateDirectories().Sum(dir => DirectorySize(dir, true));
            //.Where(d => (d.Attributes & FileAttributes.ReparsePoint) == 0 && (d.Attributes & FileAttributes.System) == 0)
            //.Sum(dir => DirectorySize(dir, true));
    }
    return totalSize;
}

I would like to get a concise LINQ method where I don't have to manually loop and test every folder/dir. I found some MS code for duplicates that operates similarly. It errors out the same too.

My thanks in advance,

Upvotes: 2

Views: 1719

Answers (2)

Dane Balia
Dane Balia

Reputation: 5367

There are other references to this in Stack Overflow; but you probably need to define permissions for your application itself. Setting Perms

There is also this little nugget [ C:\Users is a JUNCTION]; C#: Access to path <'filepath'> is denied

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039298

try/catch to the rescue as demonstrated in the following article. There are also alternatives.

Upvotes: 0

Related Questions