开发者

Check if a list already exists before creating it

I am creating a list definition and a list instance with xml code in my SharePoint 2010 solution. Now, each time I deploy my solution it deletes the list and creates a new one. I only want to create the list if it doesn't exist.

How do I check if the list already exists and where do I put the code?

My list definition and list instance appear among "Items in the Feat开发者_高级运维ure" in one of my features.


Thank you for your answers. I found the solution in the SharePointProjectItem.spdata file located in the list instance folder. Setting "DeploymentConflictResolutionBehavior" to "None" stopped Visual Studio from deleting my list on every deploy.

My SharePointProjectItem.spdata file now looks like this:

<?xml version="1.0" encoding="utf-8"?>
<ProjectItem Type="Microsoft.VisualStudio.SharePoint.ListInstance" DefaultFile="Elements.xml" SupportedTrustLevels="All" SupportedDeploymentScopes="Web, Site" xmlns="http://schemas.microsoft.com/VisualStudio/2010/SharePointTools/SharePointProjectItemModel">
  <Files>
    <ProjectItemFile Source="Elements.xml" Target="MyListInstance\" Type="ElementManifest" />
  </Files>
  <ExtensionData>
    <ExtensionDataItem Key="DeploymentConflictResolutionBehavior" Value="None" />
  </ExtensionData>
</ProjectItem>


There is no method currently included in SP object model to determine this. As Beytan mentioned, an extension method can help solve this issue. I think the example in this link is a better way to implement this type of extension method. It iterates through the entire collection of lists, returning true if it finds a match and false if it does not. The following is the code from the post.

public static class SPWebExtensions
{
    public static bool ListExists(this SPWeb web, string listName)
   {
          var lists = web.Lists;
          foreach (SPList list in lists)
          {
              if(list.Title.Equals(listName))
                  return true;
          }
          return false;
      }
  }

Since your list definitions and instances are already in a feature, you can call the extension method from the FeatureActivated method of the event receiver for your feature.

using(SPWeb web = (SPWeb)properties.Feature.Parent)
{
   if(!web.ListExists(listTitle))
   {
      //create the list.
   }
}


Create instance from code (web.Lists.Add), and use this to check if already exists: web.Lists.TryGetList("listTitle")


How to check if SPList exists via Server Side Object Model:

//Verify if list exist by its Url 
public static bool ListExists(SPWeb web, string listUrl)
{
   return web.Lists.Cast<SPList>().Any(list =>  string.Equals(list.RootFolder.ServerRelativeUrl, listUrl));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜