SharePoint 2010: Downloading a Document using a Client Object Model



Here is the code snippet that aids in downloading a document residing on a specific document library and further on folders hierarchy.

public string DownloadDocument(string siteURL, string spPath, string strFileName)
        {
            try
            {
                clientContext = new ClientContext(siteURL);
               //Here is the punch...if the document is in a document library residing in a subsite then siteURL
               //must contain the Name of subsite. 
               //spPath is the location where the required document resides. 

                FileInformation fInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext,spPath);

               //Path where you want to save the file
                string strPath = "C:\\Temp\";
                FileStream writeStream = new FileStream(strPath, FileMode.Create, FileAccess.Write);

                int Length = 256;
                Byte[] buffer = new Byte[Length];
                int bytesRead = fInfo.Stream.Read(buffer, 0, Length);
                // write the required bytes
                while (bytesRead > 0)
                {
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = fInfo.Stream.Read(buffer, 0, Length);
                }
                fInfo.Stream.Close();
                writeStream.Close();
                if (clientContext != null)
                {


                    clientContext.Dispose();
                }
                return strPath;
            }
            catch (Exception)
            {

                throw;
            }

        }

Comments

  1. what namespace is required except the microsoft.sharepoint.client reference to have FileInformation and File.OpenBinaryDirect ?
    both the names doesnot exist in this namespace.

    ReplyDelete

Post a Comment

Popular posts from this blog

SPFx: Develop using SharePoint Framework without Installing all the dependecies.

SharePoint Online: Elevated Permissions....with love

Powershell: Filling up an Existing Excel Sheet with data from SQL Server