Thursday, December 27, 2012

Create Folders in a Sharepoint Library through Code

Hi
 
In this post I'll explain how to create folders in a sharepoint library using C# Code.

This will be useful when you have to create custom folder structures in a sharepoint library.

First you'll need a shapoint Document Library which you are going to add folders to.

Here I'm using the library named 'My Documents' and creating a folder named 'New Folder'

using(SPSite mySite=new SPSite("http://mysite"))
{
 using(SPWeb myWeb=mySite.OpenWeb())
 {
  //Get the Folder Library
  SPList MyFiles = myWeb.Lists["My Documents"];

  //Create the URL for the Folder Library
  //You can have a string variable for url on top and use it here as well
  string folderURL = myWeb.Url + "/" + MyFiles.Title;

  //Set the name for the folder
  string folderName="New Folder";

  //Create the folder inside the library
  SPListItem OpportunityFolder = MyFiles.Items.Add(url, SPFileSystemObjectType.Folder, folderName);
  OpportunityFolder.Update();
 }
}
 
Now we'll see how to delete the folder we created.

using(SPSite mySite=new SPSite("http://mysite"))
{
 using(SPWeb myWeb=mySite.OpenWeb())
 {
  //Get the document folder library
  SPList MyFiles = myWeb.Lists["My Documents"];
  //Get the folder url
  string url = myWeb.Url + "/" + MyFiles.Title;
  //Get the folder name
  string folderName = "New Folder";
  //Delete the created folder
  properties.Web.Folders["My Documents"].SubFolders.Delete(folderName);
 }
}
 
Hope this is useful
Please leave a comment

No comments:

Post a Comment