Listing all files on my computer and sorting by size

后端 未结 3 1346
遥遥无期
遥遥无期 2021-01-13 08:55

Recently I\'ve come into the problem that my hard drive is getting obnoxiously full, but after going through my personal files and deleting/moving all of the oversized video

相关标签:
3条回答
  • 2021-01-13 09:32

    Does it have to be in c#? Try this from a command prompt: dir c: /B /O-S /S /4 /a-d > fileList.txt

    The dir command lists files, /B removes a bunch of info guff, /O-S displays the files in Order (by (S)Size (-)descending and goes through all subdirectories due to /S. The /4 bit just sets the year of files to four digits in case you have some from last century, and the /a-d weeds out the directory listings.

    0 讨论(0)
  • 2021-01-13 09:34

    Try another overload of GetFiles:

    string[] fns = Directory.GetFiles(dir, "*", SearchOption.AllDirectories);
    

    Also it will be more efficiently if you use EnumerateFiles:

    const string dir = "C:\\";
    var Sort = Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)
                        .OrderByDescending(f => new FileInfo(f).Length);
    foreach (string n in Sort)
    {
            Console.WriteLine(n);
    }
    

    To avoid exceptions:

    const string dir = "C:\\";
    var fileInfos = new List<FileInfo>();
    GetFiles(new DirectoryInfo(dir), fileInfos);
    fileInfos.Sort((x, y) => y.Length.CompareTo(x.Length));
    foreach (var f in fileInfos)
    {
        Console.WriteLine(f.FullName);
    }
    
    private static void GetFiles(DirectoryInfo dirInfo, List<FileInfo> files)
    {
        // get all not-system subdirectories
        var subDirectories = dirInfo.EnumerateDirectories()
            .Where(d => (d.Attributes & FileAttributes.System) == 0);
        foreach (DirectoryInfo subdirInfo in subDirectories)
        {
            GetFiles(subdirInfo, files);
        }
        // ok, now we added files from all subdirectories
        // so add non-system files from this directory
        var filesInCurrentDirectory = dirInfo.EnumerateFiles()
            .Where(f => (f.Attributes & FileAttributes.System) == 0);
        files.AddRange(filesInCurrentDirectory);
    }
    
    0 讨论(0)
  • 2021-01-13 09:46

    So I put my programmer brain to work and decided that instead of meticulously going through each folder and > subfolder myself and using the right-click + Properties function of Windows to see how big a file is and whether or not its worth keeping around, I could write a simple code that would search for every file on my > computer, throw it into a list by its full path name, and put its file size right next to it, then sort it from greatest to least by file size.

    While this is a fun programming exercise, if your goal is to solve the problem at hand, there is a nice utility that will do this for you: WinDirStat

    0 讨论(0)
提交回复
热议问题