Thursday, April 15, 2010
Delete ContentType from a Library
This is a Console Application. Build it and .exe file is generated. Can move to other environments with running .exe from where it is added.
ChangeContentType.exe http://YourBox/ TempLib 1stContentType(Form) NewContentType DestinationLibrary
static void Main(string[] args)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(args[0])) //"http://YourBox/"))
{
using (SPWeb web = site.RootWeb)
{
//args[1] = TempLib
//Create a temporary Library, where we move all the Destination Library list items.
web.Lists.Add(args[1], args[1], SPListTemplateType.DocumentLibrary);
SPList destLib = web.Lists[args[1]];
SPList list = web.Lists[args[1]]; //"DestinationLib"];
//Move all the list items from "DestinationLib" to "TempLib".
int count = list.Items.Count;
for (int j = count; j >0; j--)
{
SPFile file = list.Items[j-1].File;
file.MoveTo(web.Url + "/" + args[1]+ "/" + file.Name);
}
try
{
//Remove "Form" 1st Content Type. args[2]="Form"
SPContentType cTypeToBeRemovedForm = list.ContentTypes[args[2]]; //"1stContentType"];
list.ContentTypes.Delete(cTypeToBeRemovedForm.Id);
//Remove "SecondContentType" Content Type. args[3] = SecondContentType
SPContentType cTypeToBeRemoved = list.ContentTypes[args[3]]; //"SecondContentType"];
list.ContentTypes.Delete(cTypeToBeRemoved.Id);
//Add "NewContentType" Content Type from the web.
SPContentType cTypeToBeAdded = web.ContentTypes[args[3]]; //"ContentTypefromweb";
list.ContentTypes.Add(cTypeToBeAdded);
list.Update();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//Move all the list items from "TempLib" to "DestinationLib". // args[4]= DestinationLib
int tempCount = destLib.Items.Count;
for (int j = count; j > 0; j--)
{
SPFile file = destLib.Items[j-1].File;
file.MoveTo(web.Url + "/" + args[4] + "/" + file.Name);
}
web.Lists[args[1]].Delete();
}
}
});
}
catch (Exception e)
{
Console.WriteLine("Exception Message - " + e.Message + "\nInner Exception - " + e.InnerException + "\nStack Trace - " + e.StackTrace);
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment