Can I get site Usage in Sharepoint online using CSOM?
-
24-01-2021 - |
Question
I want to get the "Site Usage Report" on a Sharepoint Online site using C#. How can I do it? This link provides solutions to get these details but I want to do it programatically using C# (CSOM).
Another question along the similar lines was asked in the past, but I believe it wasn't answered satisfactorily.
Solution
The following code retrives the Usage Info but sadly, the Hits and Visits shows 0 because of this reason.
clientContext.Load(clientContext.Site, s => s.Usage);
try
{
clientContext.ExecuteQuery();
UsageInfo usageInfo = clientContext.Site.Usage;
usageData = "No. of hits: " + Convert.ToString("" + usageInfo.Hits) + "; ";
usageData += "No. of visits: " + Convert.ToString("" + usageInfo.Visits) + "; ";
usageData += "Storage: " + Convert.ToString("" + usageInfo.Storage) + "; ";
usageData += "Storage Percentage Used: " + Convert.ToString("" + usageInfo.StoragePercentageUsed) + "; ";
var bytes = usageInfo.Storage;
Debug.Print("UsageData " + usageData);
Debug.Print("Bytes " + bytes);
}
OTHER TIPS
Yes you can. To access the Site Usage info, you must have a sharepoint admin. You must load site.Usage property before accessing it.
using (var ctx = new ClientContext("siteUrl"))
{
var userName = "userName";
var password = "password";
var securePassword = new SecureString();
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);
ctx.Load(ctx.Site, s => s.Usage);
ctx.ExecuteQuery();
UsageInfo usageInfo = ctx.Site.Usage;
Console.WriteLine("Storage Usage: " + usageInfo.Storage.ToString());
Console.ReadKey();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange