Search This Blog

Thursday, November 27, 2014

How to Upload and Download Document from DocLibrary In SharePoint 2010

Upload Document:

String fileToUpload = @"C:\YourFile.txt";         
String sharePointSite = "http://yoursite.com/sites/Research/";         
String documentLibraryName = "Shared Documents";         
using (SPSite oSite = new SPSite(sharePointSite))         
{             
using (SPWeb oWeb = oSite.OpenWeb())             
{
  if (!System.IO.File.Exists(fileToUpload))                     
throw new FileNotFoundException("File not found.", fileToUpload);                 
SPFolder myLibrary = oWeb.Folders[documentLibraryName];                 
// Prepare to upload                 
Boolean replaceExistingFiles = true;                 
String fileName = System.IO.Path.GetFileName(fileToUpload);                 
FileStream fileStream = File.OpenRead(fileToUpload);                 
// Upload document                 
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);                 
// Commit                 
myLibrary.Update();             
}         
} 
Download Document:
SPList currentLib = web.Lists["LibraryName"];
Get all items from the document library
foreach (SPListItem item in items)
{

byte[] binfile = item.File.OpenBinary();
FileStream fstream = new FileStream("C:\\" + item.File.Name,
FileMode.Create, FileAccess.ReadWrite);
fstream.Write(binfile, 0, binfile.Length);
fstream.Close();
}

No comments:

Post a Comment