For those of you that are not familiar with the Property Bag concept, it is a place to store metadata or properties for your SharePoint objects. However, when exploring the SharePoint object model, I have noticed that SPWeb provides a Property bag to store metadata info related to a web site, where SPSite doesn’t. So the only way to store metadata info related to a site collection (SPSite) is to use the property bag of the root web.
SPSite Represents a collection of sites on a virtual server, including a top-level site and all its subsites.
SPWeb Represents a Windows SharePoint Services Web site.
To store a property in the bag :
SPPropertyBag Bag = site.RootWeb.Properties; if (!Bag.ContainsKey("PropertyName")) { Bag.Add("PropertyName", "PropertyValue"); Bag.Update(); }
And to remove a property, use the following snippet :
SPPropertyBag Bag = site.RootWeb.Properties; if (Bag.ContainsKey("PropertyName")) { Bag["PropertyName"]=null; Bag.Update(); }
For more SharePoint code snippets, I would recommend SPCodeSnippets available at codeplex.