Showing posts with label Upload. Show all posts
Showing posts with label Upload. Show all posts

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.