在C#中使用FileSystemObject时出现安全异常 [英] Security Exception while use FileSystemObject in C#

查看:323
本文介绍了在C#中使用FileSystemObject时出现安全异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个快速的磁盘使用率检测程序,发现FileSystemObject是最快的方法.而FileSystemObjectCOM -> Microsoft Scripting Runtime中.

I want to write a fast disk usage detect program, and found that FileSystemObject is the fastest way to do this. And FileSystemObject is in COM -> Microsoft Scripting Runtime.

所有代码都很简单,我在这里进行了解析.

All the code is simple, and I parsed here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiskUsage
{
    class Program
    {
        const string FolderPath = @"C:\Windows\System32";

        static void Main(string[] args)
        {
            var startTime = DateTime.Now;

            Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
            Scripting.Folder folder = fso.GetFolder(FolderPath);
            Int64 dirSize = (Int64)folder.Size;

            TimeSpan span = DateTime.Now.Subtract(startTime);

            System.Console.WriteLine("{1} size: {0}", dirSize, FolderPath);
            System.Console.WriteLine("use time: {0}", span);
            System.Console.ReadKey();
        }
    }
}

然后将app.manifest设置为

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

当我测试程序时,此行出现安全异常

When I test my program, Security exception come at this line

Int64 dirSize = (Int64)folder.Size;

异常信息(我手动翻译,对不起我的英语.)是

The Exception Info( I translate manually, sorry for my poor English. ) is

Unhandled exception type "System.Security.SecurityException" occurred in DiskUsage.exe 
Other message: exception from HRESULT:0x800A0046 (CTL_E_PERMISSIONDENIED)

如果我将FolderPath更改为@"D:\Codes".它工作正常.因此,我认为清单中的安全性设置对COM -> Microsoft Scripting Runtime无效.有人知道怎么修这个东西吗?请帮助,谢谢.

If I change FolderPath to @"D:\Codes". It works fine. So I think the security setting in manifest is not effect to COM -> Microsoft Scripting Runtime. Anyone know how to fix this? Please help, thanks.

推荐答案

调用Size属性会发生魔术.在内部,它仍然遍历整个文件夹树及其文件,以确定文件夹的大小.如果您当前的身份(提升与否)没有权限在您不走运的任何子文件夹中列出文件,则对Size的调用将失败.

There is magic happening when that Size property is called. Internally it still traverses the full folder tree and it's files to determine the size of the folder. If your current identity, elevated or not, doesn't have permission to list the files in any subfolder you're out of luck, the call to Size will fail.

我改用System.IO中的Directory类重新实现了文件夹遍历,但是添加了一些日志记录和异常处理,因此它将告诉您文件夹的大小,至少对于您可以访问的文件而言

I've instead re-implemented the folder traversal using the Directory class found in System.IO but added some logging and exception handling so it will tell you the size of the folder, at least for the files you've access to.

您的主要方法需要进行以下更改:

Your main method needs to have this change:

Int64 dirSize;
try { 
    dirSize = (Int64)folder.Size;
}
catch(SecurityException sec)
{
    dirSize = FolderSize(FolderPath);
}

如果遇到异常,我们将调用FolderSize的c#实现,但这一次它将补偿未授权的异常.

If you run into the exception we make a call to the c# implementation of FolderSize but this time it will compensate for the Unauthorized exceptions.

static Int64 FolderSize(string path)
{
    long sum =0;
    try
    {
        // scan folders
        foreach(var dir in Directory.EnumerateDirectories(path))
        {
            //recursive call
            sum += FolderSize( dir);
        }
    } 
    catch(UnauthorizedAccessException unath)
    {
        Console.WriteLine("{0} for folder {1}", unath.Message, path);
    }
    try
    {
        // scan files
        foreach (var file in Directory.EnumerateFiles(path))
        {
            sum += new FileInfo(file).Length;
        }
    }
    catch(UnauthorizedAccessException filesec)
    {
        Console.WriteLine("{0} for file {1}", filesec.Message, path);
    }
    return sum;
}

这篇关于在C#中使用FileSystemObject时出现安全异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆