If you find a more appreapiate way of naming the title of this question please feel free to update it.
I have the Node
public Class Node
{
public List<Node> Children = new List<Node>();
public Node Parent;
public FileSystemInfo Value;
}
to represent a file in a tree.
Now I will like to change that node class for:
class ScanItem
{
public List<ScanItem> Children;
public ScanItem Parent;
public long Size;
public string Name;
public string FullPath;
public bool IsDirectory;
// etc....
}
So my question is how will I be able to cast a Node class object to a ScanItem. I will like to store the size of files and directories not just files. (Node class only stores sizes of files not directories) Therefore I will have to somehow recursively keep track of the sum of the sizes of children in order to achieve what I want.
So far I have placed this constructor on ScanItem:
public ScanItem(Node node)
{
this.Name = node.Name;
this.FullPath = node.Value.FullName;
foreach(var child in node.Children)
{
this.Children.add(new ScanItem(child));
}
}
That will enable me to perform the cast but I am missing to assign the sizes of directories...
To get the size of a directory you can use this extension method
public static class DirectoryInfoEx
{
public static long GetDirectorySize(this DirectoryInfo di)
{
long size = 0;
var fileInfos = di.GetFiles();
foreach (var fi in fileInfos)
{
size += fi.Length;
}
var subDirInfos = di.GetDirectories();
foreach (var subDir in subDirInfos)
{
size += GetDirectorySize(subDir);
}
return size;
}
}
If I got this correctly, you will just need to add two lines of code in the constructor of the ScanItem class
public ScanItem(Node node)
{
this.Name = node.Name;
this.FullPath = node.Value.FullName;
DirectoryInfo di = new DirectoryInfo(this.FullPath); //<<<<<<<
this.Size = di.GetDirectorySize(); //<<<<<<<
foreach(var child in node.Children)
{
this.Children.add(new ScanItem(child));
}
}
You may need to handle some exceptional situations like UnauthorizedAccessException. You can also improve your style by getting rid of public fields, for example by converting them into public auto properties public long Size{get;set;}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With