0

I have limited the size of the content database upto 200 GB. I have used the following code to get the size of a content database.

SPWebApplication elevatedWebApp = spWeb.Site.WebApplication;
SPContentDatabaseCollection dbCollection = elevatedWebApp.ContentDatabases;
//Guid id = dbCollection[0].Id;

Guid lastContentDbGuid = new Guid(contentDbGuid);
//SPContentDatabase lastDatabase = dbCollection[dbCollection.Count - 1]; 

SPContentDatabase lastDatabase = dbCollection[lastContentDbGuid];
ulong dbSize = lastDatabase.DiskSizeRequired;
contentDbMB = ConvertToMegabytes(dbSize);

static string ConvertToMegabytes(ulong bytes)
{
    return ((decimal)bytes / 1024M / 1024M).ToString("F1") + "MB";
}

Similary I want to limit a site collection upto 100 GB. So I am using the following code

long bytes = spSite.Usage.Storage;
double siteCollectionSizeInMB = ConvertBytesToMegabytes(bytes);

>

static double ConvertBytesToMegabytes(long bytes)
{
    return (bytes / 1024f) / 1024f;
}

I need the size of collection using C# only. Am I doing it right way ? If I am doing anything wrong then please guide me. If anyone is having different solution then please share.

roybalderama
  • 1,650
  • 21
  • 38
Shailesh Jaiswal
  • 3,606
  • 13
  • 73
  • 124

3 Answers3

0

Look at the two solutions here: Theres both a powershell and c# solution i.e. the C# solution to get the collection size is:

SPWebService service = SPFarm.Local.Services.GetValue<SPWebService>();
    foreach (SPWebApplication webapp in service.WebApplications)
    {
        Console.WriteLine("WebApplication : " + webapp.Name);
        foreach (SPContentDatabase db in webapp.ContentDatabases)
        {
            Console.WriteLine("{0}, Nb Sites : {1}, Size : {2}, ", db.Name, db.Sites.Count, db.DiskSizeRequired);
        }
    }

You could use the following to get the total DB size etc (Taken from here):

Server srv new Server();

Database db = srv.Databases("MyDatabase");

\\Display size and space information for the database.
Console.WriteLine("data space usage (KB): " + db.DataSpaceUsage.ToString);
Console.WriteLine("index space usage (KB): " + db.IndexSpaceUsage.ToString);
Console.WriteLine("space available (KB): " + db.SpaceAvailable.ToString);
Console.WriteLine("database size (MB): " + db.Size.ToString);
Community
  • 1
  • 1
Paul Zahra
  • 9,522
  • 8
  • 54
  • 76
0

C# uses essentially the same structure as Powershell in this case and a good example can be found here.

using(SPSite site = new SPSite(http://yoursitehere.com/site)
{
    SPSite.UsageInfo usageInfo = site.UsageInfo;
    long storageReq = usageInfo.Storage;
}

If you need to iterate through each site in a content database, just call the content database object and reference its .sites property.

NotVonKaiser
  • 198
  • 6