Delete field (column) from a SharePoint list Using C#(CSOM)

            string strUrl = ConfigurationManager.AppSettings["SiteUrl"]; 
            string strWebUrl = ConfigurationManager.AppSettings["WebUrl"];
            string strListName = ConfigurationManager.AppSettings["ListName"];
            string strFieldName = ConfigurationManager.AppSettings["FieldName"];

            Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate ()
            {
                using (SPSite site = new SPSite(strUrl))
                {
                    using (SPWeb web = site.OpenWeb(strWebUrl))
                    {
                        web.AllowUnsafeUpdates = true;
                        SPList list = web.Lists[strListName];
                        if (list != null)
                        {
                            foreach (SPField field in list.Fields)
                            {  
                                if (field.Title == strFieldName)
                                {
                                    field.AllowDeletion = true;
                                    field.Delete();
                                    list.Update();
                                    break;
                                }
                            }
                        }
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });

            Console.WriteLine("Success");

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
posted @ 2021-02-08 15:25  SelenaZhou  阅读(61)  评论(0编辑  收藏  举报