Retrieve content type id by content type name using client object model code SharePoint online


Here we will discuss how we can retrieve content type id by content type name using client object model in SharePoint online. we will use here C#.net managed object model code and we are using here Microsoft.SharePoint.Client.dll.

The below method will take two parameters as: URL and contentTypeName. Here URL is the site url and contentTypeName is the content type name for which we are trying to retrieve the content type id.


This we are doing in a console application and we are connecting to a SharePoint online site.



public static string GetContentTypeIdByName(string URL, string contentTypeName)
{
string contentTypeId = string.Empty;
using (ClientContext clientContext = new ClientContext(URL))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
Web rootWeb = clientContext.Site.RootWeb;
var itemContentType = clientContext.LoadQuery(rootWeb.ContentTypes.Where(ct => ct.Name == contentTypeName));
clientContext.ExecuteQuery();
var sessionContentType = itemContentType.FirstOrDefault();
contentTypeId = sessionContentType.Id.ToString();
}
return contentTypeId;
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings[“SPOPassword”])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings[“SPOAccount”];
}
catch
{
throw;
}
}

Read some sharepoint online tutorials:

Hope this will be helpful.

Check out Best Alternative to InfoPath -> Try Now

EnjoySharePoint YouTube Channel

About Bhawana Rathore

Hello Everyone!! I am Bhawana a SharePoint MVP and having about 8+ years of SharePoint experience as well as in .Net technologies . I have worked in all the versions of SharePoint from wss to Office 365. I have good exposure in Customization and Migration using Nintex, Metalogix tools . Now exploring more in SharePoint 2016 :) Hope here I can contribute and share my knowledge to the fullest. As I believe "There is no wealth like knowledge, and no poverty like ignorance"

View all posts by Bhawana Rathore →