Better Way to Get Directory Size

G

Guest

I have the following function to get the directory sizse, i wondering if
there any better way to find directory size


public static double GetDirectorySize(string DirectoryPath)
{
double fDirSize = 0 ;

if(!System.IO.Directory.Exists(DirectoryPath))
return fDirSize;
try
{
System.IO.DirectoryInfo dirInfo = new
System.IO.DirectoryInfo(DirectoryPath);


System.IO.FileInfo[] oFiles = dirInfo.GetFiles();
if(oFiles.Length > 0 )
{
int nFileLen = oFiles.Length;
for (int i=0 ; i < nFileLen ; i++)
fDirSize += oFiles.Length ;
}

System.IO.DirectoryInfo[] oDirectories = dirInfo.GetDirectories();
if (oDirectories.Length > 0 )
{
int nDirLen = oDirectories.Length;
for (int i=0 ; i < nDirLen ; i++)
fDirSize += GetDirectorySize(oDirectories.FullName);
}
}
catch(System.Exception ex)
{
throw new System.IO.IOException("GetDirectorySize >>" + ex.Message + ">>" +
ex.StackTrace);
}

return fDirSize ;
}
 
K

Karl Seguin

Other than the fact that you can write the code more compactly, that's the
only way:

public static long Size(System.IO.DirectoryInfo dirInfo)
{
long total = 0;
foreach(System.IO.FileInfo file in dirInfo.GetFiles())}
total += file.Length;
}

foreach(System.IO.DirectoryInfo dir in dirInfo.GetDirectories()){
total += Size(dir);
}
return total;
}

Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top