Sunday, November 14, 2010

Code to download document from SharePoint Document Library

string siteURL = "http://mysite: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 = 
       Path.Combine(Environment.GetFolderPath
                          (Environment.SpecialFolder.LocalApplicationData),
                        "MyFolder");

        //Create directory if it not exist
        if (!(Directory.Exists(directoryPath)))
        {
            Directory.CreateDirectory(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);
        bw.Write(binFile);
        bw.Close();
    }
}

No comments:


A sales engineer is someone who promise you a bridge, even when there's no river.