gt2jmq
Last Updated: February 25, 2016
·
6.573K
· arivazhagan
2bc044e8db9c92bb62109d86ba5e8c6c

Check the field/content type/list already exist in SharePoint site using c# [CSOM client]

As i working on creating content type, site columns and lists there is some field name is always conflict with my desired column name so here is a helper function to get over with that nasty exceptions. The model for all the field remain same except the collection like List,Content type, Site Column collection, I made it simple by return back the field count,
1. If count is zero, field doesn't exist
2. if cont is not zero, field exist
I hope this may helpful for some,

public dynamic isExist_Helper(ClientContext context, String fieldToCheck,String type)
{
    var isExist = 0;
    ListCollection listCollection = context.Web.Lists;
    ContentTypeCollection cntCollection = context.Web.ContentTypes;
    FieldCollection fldCollection = context.Web.Fields;
    switch (type) { 
        case "list":
            context.Load(listCollection, lsts => lsts.Include(list => list.Title).Where(list => list.Title == fieldToCheck));
            context.ExecuteQuery();
            isExist = listCollection.Count;
        break;
        case "contenttype":
            context.Load(cntCollection, cntyp => cntyp.Include(ct => ct.Name).Where(ct => ct.Name == fieldToCheck));
            context.ExecuteQuery();
            isExist = cntCollection.Count;
        break;
        case "contenttypeName":
        context.Load(cntCollection, cntyp => cntyp.Include(ct => ct.Name, ct => ct.Id).Where(ct => ct.Name == fieldToCheck));
        context.ExecuteQuery();
        foreach (ContentType ct in cntCollection)
        {
            return ct.Id.ToString();
        }
        break;
        case "field":
            context.Load(fldCollection, fld => fld.Include(ft => ft.Title).Where(ft => ft.Title == fieldToCheck));
            try
            {
                context.ExecuteQuery();
                isExist = fldCollection.Count;
            }
            catch (Exception e) {
                if (e.Message == "Unknown Error")
                {
                    isExist = fldCollection.Count;
                }
            }
        break;
        case "listcntype":
        List lst = context.Web.Lists.GetByTitle(fieldToCheck);
        ContentTypeCollection lstcntype = lst.ContentTypes;
        context.Load(lstcntype, lstc => lstc.Include(lc => lc.Name).Where(lc => lc.Name == fieldToCheck));
        context.ExecuteQuery();
        isExist = lstcntype.Count;  
        break;
}
    return isExist;
}
Say Thanks
Respond