Problem
When you are working with features and you’re removing your list instance in code. Sometimes, it can happen that the list is still present in SharePoint.
A list, survey, discussion board, or document library cannot have the same name as another list, survey, discussion board, or document library in this Web site. Use your browser’s Back button, and type a new name.
You can’t really reproduce this error as it happens “sometimes” (we love this sharepoint behaviour, don’t we
– there will be a reason for this tough).
In my case, I’ve had a feature that created a Document Library in the elements.xml file.
Deleting it afterwards in Code with a ListItemRemove Object.
foreach (SPElementDefinition elementFile in elementFiles)
{
if (elementFile.ElementType == "ListInstance")
{
string defaultResourceFile = properties.Feature.Definition.DefaultResourceFile;
string listTitle = SPUtility.GetLocalizedString(elementFile.XmlDefinition.Attributes["Title"].Value, defaultResourceFile, Convert.ToUInt32(ci.LCID));
SPList list = web.Lists[listTitle];
list.Delete();
}
}
The list has been deleted from SharePoint because you can’t see it anymore (View All Site Content link in the QuickLaunch Menu):
- Browsing the List URL (WebDocs – as named in the elements.xml) gave a 404 error.
- Creating a new List with the same name in code behind throws the famous “already exists” error.
- Creating a new List in SharePoint works but the internal representation (eg. the URL) has been affixed by a number. (eg. WebDocs1 instead of WebDocs).
Google did not know the answer, people were encountering the problem but there wasn’t a solution anywhere. So let’s see what worked for me:
Solution
While debugging some other code, I saw my list in the SharePoint Web Object as a Folder. After deletion I was able to create a new list with the same name.
So basically, the SPList has been removed from the system but the SPFolder object is still there. So let’s remove the folder also if it still exists after removing the List instance.
using (SPSite objSite = new SPSite(SPContext.Current.Site.ID))
{
// get reference to the web application or web site
using (SPWeb objWeb = objSite.OpenWeb())
{
try
{
objWeb.Folders["InternalNameOfSPList"].Delete(); // Expression has been evaluated and has no value
// if you have a an exception of type 'System.ArgumentException' base {System.SystemException}: {"Value does not fall within the expected range."} it means that it was already deleted from the Folders. So we don't do anything.
}
catch (ArgumentException ex)
{
if (ex.Message != "Value does not fall within the expected range.")
{
throw new Exception();
}
}
}
}
I’m glad this solved my problem!!