Apart of manually creating, updating and deleting Sitecore items and its fields content we can also do the same activity programmatically. This helps when we need to create Sitecore content quickly from a excel sheet, csv or external database.
First, we will see how we can create an item by code.
Create Item in Sitecore
//Get the database reference where the item will be created.
Database msDB = Sitecore.Configuration.Factory.GetDatabase(“master”);
Or context DB
Database msDB = Sitecore.Context.Database;
//Get the content node or parent node where to create the item
Item parentItm = masterDb.Items[“/sitecore/content/home”];
//get the schema of the item, template on which item will be created
TemplateItem templateItm = msDB.GetTemplate(“sample/sample item”);
//Add it to the content tree
parentItm.Add(“ItemName”, templateItm);
This code should be enclosed inside below using statement.
Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(@”sitecore\User001″, false);
using (new Sitecore.Security.Accounts.UserSwitcher(User001))
{ // code goes here }
Here User001 account should be setup correctly so that he has the necessary access rights to add the items in sitecore.You can use SecurityDisabler also but there is a difference when we should use UserSwitcher vs SecurityDisabler .See my next post https://techcmsblogsrohit.com/difference-in-userswitcher-and-securitydisabler/