我如何获得一个目录大小在C#(目录中的文件)? [英] How do I get a directory size (files in the directory) in C#?

查看:231
本文介绍了我如何获得一个目录大小在C#(目录中的文件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够得到使用C#的本地目录中的一个的尺寸。我试图避免以下(伪像code),但在最坏的情况下,我将不得不接受这样的:

I want to be able to get the size of one of the local directories using C#. I'm trying to avoid the following (pseudo like code), although in the worst case scenario I will have to settle for this:

    int GetSize(Directory)
    {
        int Size = 0;

        foreach ( File in Directory )
        {
            FileInfo fInfo of File;
            Size += fInfo.Size;
        }

        foreach ( SubDirectory in Directory )
        {
            Size += GetSize(SubDirectory);
        }
        return Size;
    }

基本上,有没有走()可用的地方,这样我可以通过目录树走?这将递归保存的经过每个子目录

Basically, is there a Walk() available somewhere so that I can walk through the directory tree? Which would save the recursion of going through each sub-directory.

推荐答案

如果您使用 Directory.GetFiles 你可以做一个递归SEACH(使用 SearchOption.AllDirectories ),但是这是有点片状反正(特别是如果你没有访问该子目录之一) - 和可能涉及一个巨大的单一阵列回来(警告克拉克松。 ..)。

If you use Directory.GetFiles you can do a recursive seach (using SearchOption.AllDirectories), but this is a bit flaky anyway (especially if you don't have access to one of the sub-directories) - and might involve a huge single array coming back (warning klaxon...).

我很乐意与递归方法,除非我能证明(通过分析)的瓶颈;然后我可能会切换到(单级) Directory.GetFiles ,使用问答LT;字符串> 来模仿递归。

I'd be happy with the recursion approach unless I could show (via profiling) a bottleneck; and then I'd probably switch to (single-level) Directory.GetFiles, using a Queue<string> to emulate recursion.

需要注意的是.NET 4.0中引入了一些调查员为基础的文件/目录列表,它保存在大阵列的方法。

Note that .NET 4.0 introduces some enumerator-based file/directory listing methods which save on the big arrays.

这篇关于我如何获得一个目录大小在C#(目录中的文件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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