Hi,
Once i went through a requirement in which i need to get the size of each and every folder. I thought if same thing i will do with the code then only folder path i need to pas and i will get the size of each and every child folder.
Below is the C-Sharp code, which gives the size of parent and child folder.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = string.Empty;
try
{
Console.Write("Enter the path of folder : ");
path = Console.ReadLine();
GetDirectorySize(path);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Task done");
}
Console.ReadLine();
}
static void GetDirectorySize(string p)
{
long size = 0;
Console.Write("Enter the file name of text file");
Console.Write("(make sure text file should be new, otherwise you may loose your content) :");
string name = Console.ReadLine();
StreamWriter sw = new StreamWriter(name + ".txt");
System.IO.DirectoryInfo dir = new DirectoryInfo(p);
FileSystemInfo[] filelist = dir.GetFileSystemInfos();
for (int i = 0; i < filelist.Length; i++)
{
long size1 = 0;
if ((filelist[i]).Attributes.ToString().IndexOf("Directory") == 0)
{
string newPath = (filelist[i]).FullName;
System.IO.DirectoryInfo dir1 = new DirectoryInfo(newPath);
FileSystemInfo[] filelist1 = dir.GetFileSystemInfos();
FileInfo[] fileInfo1;
fileInfo1 = dir1.GetFiles("*", SearchOption.AllDirectories);
for (int i1 = 0; i1 < fileInfo1.Length; i1++)
{
try
{
size1 += fileInfo1[i1].Length;
}
catch { }
}
//Write a line of text
sw.WriteLine("Sub Folder : " + newPath + " : Directory size in MB : " + Math.Round((((double)size1) / (1024 * 1024)),2));
}
}
FileInfo[] fileInfo;
fileInfo = dir.GetFiles("*", SearchOption.AllDirectories);
for (int i = 0; i < fileInfo.Length; i++)
{
try
{
size += fileInfo[i].Length;
}
catch { }
}
sw.WriteLine("Root Folder : " + p + " : Directory size in MB : " + Math.Round((((double)size) / (1024 * 1024)),2));
//Close the file
sw.Close();
}
}
No comments:
Post a Comment