Friday 27 May 2011

Creating folder in a document library and creating file inside that folder

In order to create programmatically folder inside library and then create file inside that folder you can use following code:

using (SPWeb web = properties.Web.Site.OpenWeb("/web"))
{
 list = web.Lists["My list"];

 SPFolderCollection collection = list.RootFolder.SubFolders;
 //Create new folder
 SPFolder folder = collection.Add("Automatically created at " + DateTime.Now.ToString().Replace(":", "-"));
 item = folder.Item;
 item[SPBuiltInFieldId.Comments] = "Automatically created";

 this.EventFiringEnabled = false;
 try
 {
  item.Update();
 }
 finally
 {
  this.EventFiringEnabled = true;
 }
}
//insert attachment to folder
if (item.Folder != null)
{
 SPFolder folder = item.Folder;
 if (properties.ListItem.Attachments.Count > 0)
 {
  SPFile file = item.Web.Site.RootWeb.GetFile(properties.ListItem.Attachments.UrlPrefix + properties.ListItem.Attachments[0]);
  byte[] imageData = file.OpenBinary();
  SPListItem contractItem = folder.Files.Add(properties.ListItem.Attachments[0], imageData).Item;
  contractItem.Update();
 }
}

No comments:

Post a Comment