按大小C#对所有文件和文件夹进行排序

时间:2018-11-24 22:04:57

标签: c# linq file sorting

我正在尝试编写一些代码,以按大小对系统上的所有文件和文件夹进行排序,然后将其放入txt文件中。例如...

x = np.zeros(1000000000000)
x.nbytes
>> 8000000000000

您得到的图片-文件夹按大小排序,所有子文件夹/文件也按文件排序(也许带有上述缩进)。到目前为止,我的代码(如下)从下载的所有文件夹中获取所有文件并对它们进行排序,然后将总大小放在文件末尾。有谁知道我从这里可以去哪里?谢谢!

/Users: 25Gb
    /Users/me: 20Gb
        /Users/me/films: 11Gb
            /Users/me/films/Shrek.mkv 6Gb
            /Users/me/films/Shrek2.mkv 5Gb
        /Users/me/Documents: 9Gb
            /Users/me/Documents: myBigFile.rar 5Gb
            /Users/me/Documents: mySmallerFile.rar 4Gb
    /Users/mum: 5Gb
        /Users/mum/documents: 5Gb
            /Users/mum/documents: mumsFile.zip 5Gb

1 个答案:

答案 0 :(得分:2)

这可能会带你到某个地方

给予

from pyspark.sql.functions import col

for c in df.columns:
    if df.filter(col(c).isNotNull()).count() == 0:
      df = df.drop(c)

课程

public static class MyExtension
{
    static readonly string[] _sizeSuffixes ={ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

    public static string ToSize(this long value, int decimalPlaces = 1)
    {
        if (value < 0) { return "-" + ToSize(-value); }

        var i = 0;
        var dValue = (decimal)value;
        while (Math.Round(dValue, decimalPlaces) >= 1000)
        {
            dValue /= 1024;
            i++;
        }

        return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, _sizeSuffixes[i]);
    }
}

用法

public class Info
{
    public Info(DirectoryInfo directoryInfo)
    {
        DirectoryInfo = directoryInfo;
        Name = directoryInfo.FullName;
    }
    public Info(FileInfo fileInfo)
    {
        Name = fileInfo.FullName;
        Size = fileInfo.Length;
    }
    public DirectoryInfo DirectoryInfo { get; }
    public string Name { get; set; }

    public long Size { get; set; }
    public List<Info> Children { get; set; } = new List<Info>();
    public List<Info> GetDirectories()
    {
        if (DirectoryInfo == null) return Children;

        var dirs = DirectoryInfo.EnumerateDirectories()
                                .Select(x => new Info(x))
                                .ToList();
        Children = dirs;
        Children.AddRange(DirectoryInfo.EnumerateFiles().Select(x => new Info(x)));
        return dirs;
    }


    public void Order()
    {
        if (Children == null) return;
        Children = Children.OrderBy(x => x.Children == null).ThenByDescending(x => x.Size).ToList();
        Children.ForEach(c => c.Order());
    }

    public void Sum() => Size = Children?.Sum(x => x.Size) ?? 0;

    public void WriteResults(StreamWriter fs, int level =0)
    {
        fs.WriteLine($"{new string(' ', level)}{Name} {Size.ToSize(3)}");
        level++;
        if (Children == null) return;
        foreach (var info in Children)
            info.WriteResults(fs, level);
    }
}