如何优化此代码以创建文档库

时间:2012-03-21 07:51:12

标签: c# algorithm sharepoint sharepoint-2010

这是sharepoint代码,但我知道c#开发人员会理解它。

我现在无法想出一种方法来优化它。 我们的想法是创建一个基于事件创建的文档库。文档库的名称是某种格式的开始日期+事件标题。

问题是用户在同一天制作了许多具有相同标题的事件。 我用一个IF做了它只复制了一次。但应该有另一种更好的方法来做到这一点。

这个想法是在doc library / 1/2/3等结尾处连接一个数字。

using (SPSite oSPSite = new SPSite(SiteUrl))
            {
                using (SPWeb oSPWeb = oSPSite.RootWeb)
                {
                    if (oSPWeb.Lists[DocumentLibraryName] == null)
                    {
                        Guid ID = oSPWeb.Lists.Add(DocumentLibraryName, DocumentLibraryName + System.DateTime.Now.ToString(), SPListTemplateType.DocumentLibrary);
                        SPList oSPList = oSPWeb.Lists[ID];
                        DocumentLibraryLink = oSPList.DefaultViewUrl;
                        oSPList.OnQuickLaunch = false;
                        oSPList.Update();
                    }
                    else
                    {
                        if (oSPWeb.Lists[DocumentLibraryName + "/1"] == null)
                        {
                            Guid ID = oSPWeb.Lists.Add(DocumentLibraryName + "/1", DocumentLibraryName + System.DateTime.Now.ToString(), SPListTemplateType.DocumentLibrary);
                            SPList oSPList = oSPWeb.Lists[ID];
                            DocumentLibraryName = DocumentLibraryName + "/1";
                            DocumentLibraryLink = oSPList.DefaultViewUrl;
                            oSPList.OnQuickLaunch = false;
                            oSPList.Update();
                        }
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:3)

在伪代码中:

string docLibNameBase ="myLibname";
string docLibNameTemp = docLibNameBase; //we start with the calculated title
int iCounter = 1;

//we check if the currently calculated title is OK
while (listExists(docLibNameTemp, yourWeb)) {
    docLibNameTemp = docLibNameBase + "/" + iCounter.toString();
}
//this is where you create the new list using docLibNameTemp as a good title


bool listExists(string docLibName, SPWeb web){
   try {
      //if there is no list with such name, it will throw an exception
      return (web.Lists[docLibname]!=null);
   } catch{
        return false;
   }
}