相关疑难解决方法(0)

在.NET中计算目录大小的最佳方法是什么?

我已编写以下例程来手动遍历目录并在C#/ .NET中计算其大小:


protected static float CalculateFolderSize(string folder)
{
    float folderSize = 0.0f;
    try
    {
        //Checks if the path is valid or not
        if (!Directory.Exists(folder))
            return folderSize;
        else
        {
            try
            {
                foreach (string file in Directory.GetFiles(folder))
                {
                    if (File.Exists(file))
                    {
                        FileInfo finfo = new FileInfo(file);
                        folderSize += finfo.Length;
                    }
                }

                foreach (string dir in Directory.GetDirectories(folder))
                    folderSize += CalculateFolderSize(dir);
            }
            catch (NotSupportedException e)
            {
                Console.WriteLine("Unable to calculate folder size: {0}", e.Message);
            }
        }
    }
    catch (UnauthorizedAccessException e)
    {
        Console.WriteLine("Unable to calculate folder …
Run Code Online (Sandbox Code Playgroud)

.net c# windows

69
推荐指数
11
解决办法
8万
查看次数

使用Directory.GetFiles(...)时拒绝访问该路径

我正在运行下面的代码并在下面获得例外.我是否被迫将此函数放入try catch中,还是以其他方式递归获取所有目录?我可以编写自己的递归函数来获取文件和目录.但我想知道是否有更好的方法.

// get all files in folder and sub-folders
var d = Directory.GetFiles(@"C:\", "*", SearchOption.AllDirectories);

// get all sub-directories
var dirs = Directory.GetDirectories(@"C:\", "*", SearchOption.AllDirectories);
Run Code Online (Sandbox Code Playgroud)

"拒绝访问路径'C:\ Documents and Settings \'."

c#

14
推荐指数
2
解决办法
4万
查看次数

需要恢复在Catch块之后尝试

从VB6时代开始,当我通过系统上的目录递归时,我能够以相对适当的方式使用"on next error next".如果我的"foreach"循环遇到Permission Denied或Access Denied错误,我所要做的就是调用"resume next"语句.

然而,在C#中,这不存在,我理解为什么.然而,令人难以理解的是在C#中弄清楚这是如何实现的.

我试图通过我的硬盘上的目录递归并填充TreeView控件.

private void PopulateTree(string dir, TreeNode node)
    {
        try
        {
            // get the information of the directory
            DirectoryInfo directory = new DirectoryInfo(dir);

            // loop through each subdirectory
            foreach (DirectoryInfo d in directory.GetDirectories("*", SearchOption.AllDirectories))
            {
                // create a new node
                TreeNode t = new TreeNode(d.Name);
                // populate the new node recursively
                PopulateTree(d.FullName, t);
                node.Nodes.Add(t); // add the node to the "master" node
            }

            // lastly, loop through each file in the directory, and …
Run Code Online (Sandbox Code Playgroud)

c#

4
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×3

.net ×1

windows ×1