Tuesday, November 24, 2009

Code to download document from SharePoint Document Library

Following code snippet demonstrate the way to download a MS Word document (or any file) from SharePoint SPDocumentLibrary-

string siteURL = "http://localhost:80/"; //Write valid site URL
//Get SPSite and SPWeb instance
using (SPSite spSite = new SPSite(sireURL))
using (SPWeb spWeb = spSite.OpenWeb())
//Get time stamp to download file with unique name
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");

//Get folder path
string directoryPath =

//Create directory if it not exist
if (!(Directory.Exists(directoryPath)))

//Get template url
string documentUrl; //Write valid document URL

//Download file in file system
SPFile myFile = spWeb.GetFile(documentUrl);
byte[] binFile = myFile.OpenBinary();

//Generate file name
filename = Path.Combine(directoryPath, strFileName + ".doc");

//Do file write operation
FileStream fs =
new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);

1 comment:

yetanotheruser said...

Thanks for the article. How do I upload a document corresponding to an event handled by a list item event receiver to a document library into an entirely different SharePoint farm? Do I need to first download and then upload, or is there any way I can open an output stream for the existing document (associated with the list item event receiver)?