Tuesday, February 26, 2013

Sharepoint create new folder in a document library and upload files using c#

Hi everyone this is a simple c# code to create a folder in sharepoint library and upload files.


using (SPSite site = new SPSite("http://cd-lroy:2222"))
{
using (SPWeb web = site.OpenWeb())
{
SPFolder myLibrary = web.Folders["SiteAssets"].SubFolders["SitePages"];
SPFolderCollection subfolders = myLibrary.SubFolders;
subfolders.Add("NewFolder");
SPFolder newFolder = subfolders["NewFolder"];
String filePath = @"C:\Users\lroy\Desktop\sharepoint-coding";

if (!System.IO.File.Exists(filePath))
throw new FileNotFoundException("File not found.", filePath);

else
{
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(filePath);
FileStream fileStream = File.OpenRead(filePath);

//Upload document
SPFile spfile = newFolder.Files.Add(fileName, fileStream, replaceExistingFiles);
newFolder.Update();
}
}
}


Added folder in the document library


Added document inside the created folder


Feel free to comment.
Cheers.

Luckshan Roy.


4 comments:

  1. Just what I was looking for...thanks Justin. what are references are you calling for this code?

    ReplyDelete
  2. Hi Martin thanks.. these are my own experience in my placement year.

    ReplyDelete
  3. This isn't for 2013, is it? SPSite SPWeb etc are not in Microsoft.SharePoint.Client namespace.

    I'm trying to overwrite an existing html document on a sharepoint document library and I'm having a hard time.

    ReplyDelete
  4. Hi, right now, I'm downloading the SharePoint 2013 SDK http://www.microsoft.com/en-us/download/details.aspx?id=30722, I hope that with this SDK and this code a can approach my goal.

    ReplyDelete