How to reprovision a document library programatically (simple example)

I have gotten a lot of questions recently around the topic of reprovisioning.  I wanted to show a simple example to get folks started.  Reprovisioning will be a topic of interest during the up and comming site definitions posts that I'm working on putting together.  I am still holding on those for now, but decided that this code sample would be worth showing.

This sample does retain versions if they are enabled.
It does not handle non-default views or customized fields.  As such, while you would retain versions, you would not retain custom metadata.  You would need the fields to be defined in the new list objects for that to be possible.  You also would want to verify metadata/etc.  I will cover some of this in another post--remember this is just a simple example.  You would need to handle a lot of these items if you were operating against a document library that is far customized from default. Also note that none of the defaults are carried over other then versioning.

I am using moveto instead of copyto because copyto does not retain versions.  It only takes the most recent object.

   // These strings would match your server, site and list name...
   SPSite mySite = new SPSite("dwinter");
   SPWeb myWeb = mySite.OpenWeb("/sites/test");
SPList myList = myWeb.Lists["test1234"];

string docLibName = myList.Title;
string docLibTemplateName = myList.BaseTemplate.ToString().Insert(myList.BaseTemplate.ToString().IndexOf("Library")," ");
SPListCollection lc = myWeb.Lists;
SPListTemplate lt = myWeb.ListTemplates[docLibTemplateName];
// Create temporary list
System.Guid newDocLibGuid = lc.Add(docLibName+"TEMP",docLibName+"TEMP", lt);
SPList newList = ((SPDocumentLibrary)(myWeb.Lists[newDocLibGuid]));
try{newList.EnableVersioning = myList.EnableVersioning;} // Lazy Try/Catch, write some error handling here
catch{}

// Move all items (including version info) from original to temporary list
foreach(SPListItem mySPListItem in myList.Items)
{
mySPListItem.File.MoveTo(newList.RootFolder.Url+"/"+mySPListItem.File.Name);
}
// Remove original list
lc.Delete(myList.ID);

// Recreate original list as a new list
System.Guid newDocLibGuid2 = lc.Add(docLibName,docLibName, lt);
SPList newList2 = ((SPDocumentLibrary)(myWeb.Lists[newDocLibGuid2]));
SPList myList2 = myWeb.Lists.GetList(newDocLibGuid,false);
try{newList2.EnableVersioning = myList2.EnableVersioning;} // Lazy Try/Catch, write some error handling here
catch{}

// Move all items (including version info) from temporary to new list
foreach(SPListItem mySPListItem2 in myList2.Items)
{
mySPListItem2.File.MoveTo(newList2.RootFolder.Url+"/"+mySPListItem2.File.Name);
}
// Remove temporary list
   lc.Delete(newDocLibGuid);

So if you were to use this, make sure you add some logging/control. This is the kind of code to play with, not the kind to drop into anything close to production.