Programatically creating a folder in Document Library for SharePoint C#/VB.Net


C# Code:

SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite oSite = new SPSite("http://sitecollection url"))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        SPList approvedlist = oWeb.Lists["Library name or list name"];
                        string foldername = Guid.NewGuid().ToString();
                        oWeb.AllowUnsafeUpdates = true;
                        SPListItem newFolder = approvedlist.Items.Add(approvedlist.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, foldername);
                        newFolder.Update();
                        oWeb.AllowUnsafeUpdates = false;
                    }
                }

            });


VB.Net Code:

 Dim newFolder As SPListItem
            Dim approvedlist As SPList
            Dim foldername As String
            Dim sysToken As SPUserToken = SPContext.Current.Site.SystemAccount.UserToken
            Using oSite As New SPSite("http://sharepoint:XXXX",sysToken)
                Using oWeb As SPWeb = oSite.OpenWeb()
                    approvedlist = oWeb.Lists("FolderName")
                    foldername = Guid.NewGuid().ToString()
                    oWeb.AllowUnsafeUpdates = True
                    newFolder = approvedlist.Items.Add(approvedlist.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, foldername)
                    newFolder.Update()
                    oWeb.AllowUnsafeUpdates = False
                End Using
            End Using

2 comments:

  1. Thanks for the solution.
    By following your approach i have written the code to support up to nth level Folders creation. Please see my approach once and give me your valuable feedback.

    http://sharepointquicksolutions.blogspot.in/2014/06/create-nth-level-of-folders-in.html

    Once again thanks for your approach

    ReplyDelete
  2. Thank you for sharing wonderful information with us to get some idea about that content. check it once through

    ReplyDelete