Share via


Creating folders and adding files to SharePoint Document Library

It is pretty easy to do that. Here is a piece of code which creates a folder in document library and adds a file to the created folder:

 SPSite site = new Microsoft.SharePoint.SPSite("https://localhost");            
SPWeb spWeb = site.RootWeb;

SPList docLib = spWeb.Lists["My Document Library"];          
SPListItem folder = docLib.Folders.Add(docLib.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, "My folder");
folder.Update();

using (FileStream fs = File.OpenRead (@"C:\TestDoc.doc"))
{
           SPFile file = folder.Folder.Files.Add("TestDoc.doc", fs);
           file.Update(); 
}

Before you run this code you must add a reference to Microsoft.SharePoint.dll which is located at:

X:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll

Also this code assumes that document library named "My Document Library" exists. If you want to create a document library you can use this code:

 spWeb.Lists.Add("My Document Library", "This is my first document library", SPListTemplateType.DocumentLibrary); 

Looks like "Insert Code" plug-in works just fine ...