Skip to content
Bruno Sonnino
Menu
  • Home
  • About
Menu

Discover what is consuming your disk with NTFS structures

Posted on 26 September 2020

Introduction

Some time ago, I wrote this post  with this accompanying source code. It showed the way to use NTFS file structures to enumerate files and show the files that take more space in your hard disk. Then a user posted a note asking if it would be possible to know if, instead of knowing the files, I could show the directories that consume more space, and I said "of course, you can do it with some minor changes!", and showed him a sample of the code.

Then I realized that that could be an interesting way to improve the program and show a little bit about working with the data we have - gather the data is important, but work with it to extract every bit of information is even more! So, let's go to it (if you haven't already read the original article, do it now).

Working with the data

The original code to retrieve all the files size using the NTFS file structures is:

var ntfsReader =
    new NtfsReader(driveToAnalyze, RetrieveMode.All);
nodes =
    ntfsReader.GetNodes(driveToAnalyze.Name)
        .Where(n => (n.Attributes &
                     (Attributes.Hidden | Attributes.System |
                      Attributes.Temporary | Attributes.Device |
                      Attributes.Directory | Attributes.Offline |
                      Attributes.ReparsePoint | Attributes.SparseFile)) == 0)
        .OrderByDescending(n => n.Size).ToList();

The reader will get all nodes from the selected drive, will filter them, removing the hidden, system, temporary and directories and will sort it by descending order. The ordering will not be necessary for our needs, because we want the directories sizes.

Before working with the data, let's create a new WPF project that will show our data in a list. In Visual Studio (you should open Visual Studio in elevated mode, because to use the NTFS structures you must have admin rights), create a new WPF project (.NET Framework) and add the dll NTFSReader from this site as a reference to the project. Then, add this code in MainWindow.xaml for our UI:

<Window x:Class="NtfsDirectories.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="30"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Margin="5">
            <TextBlock Text="Drive" VerticalAlignment="Center"/>
            <ComboBox x:Name="DrvCombo" Margin="5,0" Width="100" 
                      VerticalContentAlignment="Center"/>
        </StackPanel>
        <StackPanel Grid.Row="0" HorizontalAlignment="Right" Orientation="Horizontal" Margin="5">
            <TextBlock Text="Level" VerticalAlignment="Center"/>
            <ComboBox x:Name="LevelCombo" Margin="5,0" Width="100" 
                      VerticalContentAlignment="Center" SelectedIndex="3" 
                      SelectionChanged="LevelCombo_OnSelectionChanged">
                <ComboBoxItem>1</ComboBoxItem>
                <ComboBoxItem>2</ComboBoxItem>
                <ComboBoxItem>3</ComboBoxItem>
                <ComboBoxItem>Max</ComboBoxItem>
            </ComboBox>
        </StackPanel>
        <ListBox x:Name="DirectoriesList" Grid.Row="1" 
                 VirtualizingPanel.IsVirtualizing="True"
                 VirtualizingPanel.IsVirtualizingWhenGrouping="True" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}" 
                                   Margin="5,0" Width="450"/>
                        <TextBlock Text="{Binding Size,StringFormat=N0}" 
                                   Margin="5,0" Width="150" TextAlignment="Right"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <TextBlock x:Name="StatusTxt" Grid.Row="2" HorizontalAlignment="Center" Margin="5"/>
    </Grid>
</Window>

That will add two comboboxes, to select the drive and level to drill down and a listbox to show the results. Then, we should add the code to get the drives in the constructor of MainWindow:

public MainWindow()
{
    InitializeComponent();
    var ntfsDrives = DriveInfo.GetDrives()
        .Where(d => d.DriveFormat == "NTFS").ToList();
    DrvCombo.ItemsSource = ntfsDrives;
    DrvCombo.SelectionChanged += DrvCombo_SelectionChanged;
}

This code will fill the drives combo with all the NTFS drives in the system. When the user changes the selection, the drive will be scanned and will get all files:

private IEnumerable<INode> nodes = null;
private async void DrvCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (DrvCombo.SelectedItem == null) return;
    var driveToAnalyze = (DriveInfo)DrvCombo.SelectedItem;
    DrvCombo.IsEnabled = false;
    LevelCombo.IsEnabled = false;
    StatusTxt.Text = "Analyzing drive";

    await Task.Factory.StartNew(() => { nodes = GetFileNodes(driveToAnalyze); });

    LevelCombo.SelectedIndex = -1;
    LevelCombo.SelectedIndex = 3;

    DrvCombo.IsEnabled = true;
    LevelCombo.IsEnabled = true;
    StatusTxt.Text = "";
}

You will notice the fact that I'm setting the LevelCombo's SelectedIndex to -1 then to 3.I do that to achieve two things: clean the directories list when the drive changes and trigger the change event for the level combo. The GetFileNodes method will scan the drive and will return a list of files in that drive:

private static IEnumerable<INode> GetFileNodes(DriveInfo driveToAnalyze)
{
    var ntfsReader =
        new NtfsReader(driveToAnalyze, RetrieveMode.All);
    return
        ntfsReader.GetNodes(driveToAnalyze.Name)
            .Where(n => (n.Attributes &
                         (Attributes.Hidden | Attributes.System |
                          Attributes.Temporary | Attributes.Device |
                          Attributes.Directory | Attributes.Offline |
                          Attributes.ReparsePoint | Attributes.SparseFile)) == 0);
}

Now, we must get the directories sizes depending on the level the user selected and add them to the listbox. This is done when the level changes in the combobox:

private void LevelCombo_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (DirectoriesList == null)
        return;
    int level = Int32.MaxValue-1;
    if (LevelCombo.SelectedIndex < 0 || nodes == null)
        DirectoriesList.ItemsSource = null;
    else if (LevelCombo.SelectedIndex < 3)
        level = LevelCombo.SelectedIndex;
    DirectoriesList.ItemsSource = GetDirectorySizes(nodes, level+1);
}

As you can see, when the level is negative, I clean the results list, and when there is a level set, I call the GetDirectoriesSizes method. If the user selects the Max level, I set the level to Int32.MaxValue. The GetDirectoriesSizes method is:

private IList<DirectorySize> GetDirectorySizes(IEnumerable<INode> nodes, int level)
{
     var directories = nodes
        .Select(n => new
        {
            Path = string.Join(Path.DirectorySeparatorChar.ToString(),
                Path.GetDirectoryName(n.FullName)
                    .Split(Path.DirectorySeparatorChar)
                    .Take(level)),
            Node = n
        })
        .GroupBy(g => g.Path)
        .Select(g => new DirectorySize(g.Key, g.Sum(d => (Int64)d.Node.Size)))
        .OrderByDescending(d => d.Size)
        .ToList();
      return directories;
}

In this case, I use LINQ to group the files in the desired level. The first Select will break the path into its parts, then will take the parts only to the level we want and rejoin the parts. This will allow us to group the files according to the wanted level. One gotcha is that, when we select level 3, for example, we will want to show all files grouped to the level 3, but we will also want those that are on the upper levels. For example, for the level 3, we will want to show the files in C:\, C:\Temp, C:\Program Files\Windows and so on. If the file is under a path more than 3 levels down, it will be grouped with the upper directory.

When you run this project, you will have something like this:

Conclusion

As you can see, once we have the data, we can work on it and obtain different views. One thing that helps a lot in C# is the use of LINQ, which allows to transform the data in a simple way. The function that we used can be extended to any level you want and will bring the good results.

All the source code for this project is in https://github.com/bsonnino/NtfsDirectories

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • May 2025
  • December 2024
  • October 2024
  • August 2024
  • July 2024
  • June 2024
  • November 2023
  • October 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • October 2020
  • September 2020
  • April 2020
  • March 2020
  • January 2020
  • November 2019
  • September 2019
  • August 2019
  • July 2019
  • June 2019
  • April 2019
  • March 2019
  • February 2019
  • January 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • June 2017
  • May 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • February 2016
  • October 2015
  • August 2013
  • May 2013
  • February 2012
  • January 2012
  • April 2011
  • March 2011
  • December 2010
  • November 2009
  • June 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • July 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007
  • July 2007
  • Development
  • English
  • Português
  • Uncategorized
  • Windows

.NET AI Algorithms asp.NET Backup C# Debugging Delphi Dependency Injection Desktop Bridge Desktop icons Entity Framework JSON Linq Mef Minimal API MVVM NTFS Open Source OpenXML OzCode PowerShell Sensors Silverlight Source Code Generators sql server Surface Dial Testing Tools TypeScript UI Unit Testing UWP Visual Studio VS Code WCF WebView2 WinAppSDK Windows Windows 10 Windows Forms Windows Phone WPF XAML Zip

  • Entries RSS
  • Comments RSS
©2025 Bruno Sonnino | Design: Newspaperly WordPress Theme
Menu
  • Home
  • About