Create folders and subfolders in Sharepoint 2013 Document Library - C#
Create a single Folder
private void CreateSingleFolder(){
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
try
{
SPDocumentLibrary documentLib = web.Lists.TryGetList("DocumentLibraryName") as SPDocumentLibrary;
string FolderPath = documentLib.RootFolder.Url + "/" + "FolderName";
web.AllowUnsafeUpdates = true;
if (!web.GetFolder(FolderPath).Exists)
{
//Create Main Folder
SPListItem newFolder = documentLib.Items.Add("", SPFileSystemObjectType.Folder, "FolderName");
newFolder.Update();
}
}
catch (Exception)
{
throw;
}
}
}
});
}
Create a SubFolders inside a main Folder
private void CreateAttachmentFolder(){
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
try
{
SPDocumentLibrary documentLib = web.Lists.TryGetList("YourDocumentLibryName") as SPDocumentLibrary;
string FolderPath = documentLib.RootFolder.Url + "/" + "MainFolderName";
string FolderPath2 = documentLib.RootFolder.Url + "/" + "MainFolderName" + "/" + "SubFolderName";
#region Folder Creation
web.AllowUnsafeUpdates = true;
if (!web.GetFolder(FolderPath).Exists)
{
//Create Main Folder
SPListItem newFolder = documentLib.Items.Add("", SPFileSystemObjectType.Folder, "MainFolderName");
newFolder.Update();
//Create NSub Folder
SPListItem SubFolder = documentLib.Items.Add(newFolder.Folder.ServerRelativeUrl, SPFileSystemObjectType.Folder, "SubFolderName");
SubFolder.Update();
}
if (!web.GetFolder(FolderPath2).Exists)
{
//Create aSubFolder
SPFolder spfolder = web.GetFolder(FolderPath);
SPListItem newFolder = documentLib.Items.Add(spfolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, "SubFolderName");
newFolder.Update();
}
web.AllowUnsafeUpdates = false;
#endregion
}
catch (Exception ex)
{
throw;
}
}
}
});
}
Comments
Post a Comment