如何在C#中获取特定文件夹的总大小?

5

我正在创建一个应用程序,为用户提供一定的内存空间,我想计算他在文件夹中使用的总空间,并向他显示已使用的总空间和剩余可用的总空间。 如何在C#中计算包括特定文件夹中所有文件的整个文件夹的大小。

3个回答

3
您可以使用以下函数计算特定文件夹的大小。
来源:https://askgif.com/blog/144/how-can-i-get-the-total-size-of-a-particular-folder-in-c/(提供者:https://askgif.com/
static String GetDriveSize(String ParticularFolder, String drive)
    {
        String size = "";
        long MaxSpace = 10485760;
        String rootfoldersize = @"~/userspace/" + ParticularFolder+ "/";
        long totalbytes = 0;
        long percentageusage = 0;

        totalbytes = GetFolderSize(System.Web.HttpContext.Current.Server.MapPath(rootfoldersize) + "" + drive + "/");
        percentageusage = (totalbytes * 100) / MaxSpace;
        size = BytesToString(totalbytes);

        return size;
    }

static long GetFolderSize(string s)
    {
        string[] fileNames = Directory.GetFiles(s, "*.*");
        long size = 0;

        // Calculate total size by looping through files in the folder and totalling their sizes
        foreach (string name in fileNames)
        {
            // length of each file.
            FileInfo details = new FileInfo(name);
            size += details.Length;
        }
        return size;
    }

static String BytesToString(long byteCount)
    {
        string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
        if (byteCount == 0)
            return "0" + suf[0];
        long bytes = Math.Abs(byteCount);
        int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
        double num = Math.Round(bytes / Math.Pow(1024, place), 1);
        return (Math.Sign(byteCount) * num).ToString() + suf[place];
    }

希望这能对您有所帮助。

2
你可以使用 DirectoryInfo.GetFilesFileInfo.Length
DirectoryInfo dir = new DirectoryInfo(@"D:\Data\User_ABC");
FileInfo[] files = dir.GetFiles();
long totalByteSize = files.Sum(f => f.Length);

如果您也想包括子目录:
FileInfo[] files = dir.GetFiles("*.*", SearchOption.AllDirectories);

1
using System;
using System.IO;

class Program
{
    static void Main()
    {
        Console.WriteLine(GetDirectorySize("C:\\Site\\"));
    }

    static long GetDirectorySize(string p)
    {
        // 1.
        // Get array of all file names.
        string[] a = Directory.GetFiles(p, "*.*");

        // 2.
        // Calculate total bytes of all files in a loop.
        long b = 0;
        foreach (string name in a)
        {
            // 3.
            // Use FileInfo to get length of each file.
            FileInfo info = new FileInfo(name);
            b += info.Length;
        }
        // 4.
        // Return total size
        return b;
        }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接