简体   繁体   中英

How to optimize this code to create document libraries

This is sharepoint code, but I know c# developers would understand it.

I cant think a way right now to optimize it. The idea is to create a document library based on the creation of an event, The name of the document library is the startdate in some format + the event title.

The problem is when the user makes many events, the same day, with the same title. I did it with an IF for only one occurence of the duplication. But there should be another better way to do it.

The idea is to concatenate a number at the end of the doc library /1/2/3 etc.

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();
                        }
                    }
                }
            }
        }

In pseudo-code:

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;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM