Introduction
It's a simple program which scans a directory recursively through the subfolders and sum up the size of the files. It also displays the size of the individual files, and eventually the total size of the directory.
Explanation
Observe the follows:
using System;
using System.IO;
We need to include System.IO
, as we are working on Files and/or Directories.
The program starts as follows:
static void Main(string[] args)
{
getFilesInfo obj = new getFilesInfo();
obj.displayFileInfo(args[0]);
Console.WriteLine("Total Size = {0}", totsize);
}
Now, let's look at the crux of the program:
protected void displayFileInfo(String path)
{
try
{
if(!Directory.Exists(path))
{
Console.WriteLine("invalid path");
}
else
{
try
{
string[] fileList = Directory.GetFiles(path);
for(int i=0; i {
if(File.Exists(fileList[i]))
{
FileInfo finfo = new FileInfo(fileList[i]);
totsize += finfo.Length;
Console.WriteLine("FILE: "+fileList[i]+" :Size>"+ finfo.Length);
}
}
}
catch( System.NotSupportedException e1)
{
Console.WriteLine("Error1"+e1.Message);
}
try
{
string[] dirList = Directory.GetDirectories(path);
for(int i=0; i {
Console.WriteLine("DIRECTORY CHANGED:" + dirList[i]);
displayFileInfo(dirList[i]);
}
}
catch( System.NotSupportedException e2)
{
Console.WriteLine("Error2:"+ e2.Message);
}
}
}
catch(System.UnauthorizedAccessException e)
{
Console.WriteLine("Error:"+ e.Message);
}
}
You should have observed that we can't find the size of a folder directly. We should sum up the size of the files it constitutes. I think it is so because a Folder is just a pointer which points to the files and other directories. It has no size by itself. And one more thing is that the methods:
Directory.GetFiles(path);
Directory.GetDirectories(path);
return not just the file/directory name but the whole path to that file/folder.