Tuesday, June 4, 2013

SharePoint Calculate size of site collection sub sites

Here is the sample code to get the size of site collections and sub sites programatically.

We have multiple ways to do this.

1. STSADM
2. Console application using Object model.

STSADM :
stsadm -o enumsites -url http://Server > C:\SizeOfSites.xml
This will create a xml file in your local drive with all the required information. We can not modify the output format for this approach.


Console Application :

Here is the code sample for the same using Console application.


static void Main(string[] args)
{
    long siteCollectionSize = 0;
    string baseUrl = "http://Servername : 10000";


    using (SPSite mainSite = new SPSite(baseUrl))
    {
        foreach (SPWeb web in mainSite.AllWebs)
        {
            long webSize = GetSPFolderSize(web.RootFolder) + web.RecycleBin.Cast<SPRecycleBinItem>().Sum(r => r.Size);

            if (web.Url.StartsWith(baseUrl))
            {
                Console.WriteLine(string.Format("({0} {1}", web.Url, FormatSize(webSize)));

                siteCollectionSize += webSize;
            }
        }
    }

    Console.WriteLine("Total Size: " + FormatSize(siteCollectionSize));
    Console.WriteLine("Operation Completed successfully..");
    Console.ReadKey(false);
}

public static long GetSPFolderSize(SPFolder folder)
{
    long folderSize = 0;

    foreach (SPFile file in folder.Files)
        folderSize += file.TotalLength
            + file.Versions.Cast<SPFileVersion>().Sum(f => f.Size);

    folderSize += folder.SubFolders.Cast<SPFolder>().Sum(sf => GetSPFolderSize(sf));

    return folderSize;
}

public static string FormatSize(long size)
{
    if (size > Math.Pow(1024, 3))
        return (size / Math.Pow(1024, 3)).ToString("#,#.##") + " GB";

    else if (size > Math.Pow(1024, 2))
        return (size / Math.Pow(1024, 2)).ToString("#,#.##") + " MB";

    else if (size > 1024)
        return (size / 1024).ToString("#,#.##") + " KB";

    else
        return size.ToString("#,#.##") + " Bytes";
}

Thank you !!!



1 comment: