18 Aug’16

Dynamics CRMDownload SharePoint file programmatically without sharing it – Dynamics CRM and ADX portal or custom portal

This blog intends to able to download a SharePoint file without sharing it using Dynamics CRM and (optionally on-prem ADX portal since we can use below approach in custom portal as well).

Many times we come across scenarios where we want to share SharePoint documents with end users on web portals without give them sharing access from SharePoint.


  1. CRM online
  2. SharePoint online
  3. Web portal code access (ADX on-prem or custom portal).

Step 1: Enable SharePoint integration with CRM.

Step 2: Custom code to access SharePoint document.

Add the following code on the page where you want to show list of SharePoint documents to the end user.

  1. CS file code:
    DataTable dt = new DataTable();
    var password = new SecureString();
                    foreach (var c in "yourpassword".ToCharArray())
    ClientContext cxt = new ClientContext("https://yourdomain.sharepoint.com/Site1");
                    cxt.Credentials = new SharePointOnlineCredentials("Username", password);
                    List list = cxt.Web.Lists.GetByTitle("Document Sharing");
                    FolderCollection fcol = list.RootFolder.Folders;
                    List<string> lstFile = new List<string>();
                    DataRow dr;
                    foreach (Folder f in fcol)
                        if (f.Name == relativeURL) //relative url of the file.
                            FileCollection fileCol = f.Files;
                            foreach (File file in fileCol)
                                dr = dt.NewRow();
                                dr["fileName"] = file.Name.ToString();
                                dr["createdOn"] = file.TimeCreated.ToShortDateString();
                                dr["fileURL"] = @"javascript:downLoadFile('" + file.ServerRelativeUrl.ToString() + "')"; //Append Javascript function to the row.
                GridView2.DataSource = dt; //GridView2 being a grid added on your .aspx page.
    GridView2.DataSource = dt; //GridView2 being a grid added on your .aspx page.

    GridView2 in .aspx page:

    //Javascript function 
    <script type="text/javascript">
            function downLoadFile(link) {
                window.open("DownloadFile?url=" + link, "_blank");
    //GridView Code
    <asp:GridView ID="GridView2" runat="server" Visible="true"
            BorderWidth="1px" BackColor="White" GridLines="Vertical"
            CellPadding="4" BorderStyle="None"
            BorderColor="#DEDFDE" ForeColor="Black">
            <FooterStyle BackColor="#CCCC99">
            <PagerStyle ForeColor="Black" HorizontalAlign="Right"
            <HeaderStyle ForeColor="White" Font-Bold="True"
            <AlternatingRowStyle BackColor="White">
                <asp:BoundField HeaderText="File Name" DataField="fileName" Visible="false" HeaderStyle-Width="10%" ItemStyle-Width="10%"
                <asp:TemplateField HeaderText="File Name" HeaderStyle-Width="10%" ItemStyle-Width="10%"
                        <%# Eval("fileName") %> 
                <asp:BoundField HeaderText="Created On" DataField="createdOn" HeaderStyle-Width="5%" ItemStyle-Width="5%"
            <SelectedRowStyle ForeColor="White" Font-Bold="True"
            <RowStyle BackColor="#F7F7DE"></RowStyle>


  2. Download File:
    Add a new blank .aspx page to the portal named ‘DownloadFile.aspx’. This page will act as bridge for portal to connect to SharePoint and authenticate for being able to download the file.

    This file will contain code to authenticate the SharePoint connection for the portal to be able to download the file.


    protected void Page_Load(object sender, EventArgs e)
                string partialURL = "";
                partialURL = Convert.ToString(Request.QueryString["url"]);
            private void downloadFile(string relativeURL)
                ClientContext cxt = new ClientContext("https://yourdomain.sharepoint.com/Site1");
                var password = new SecureString();
                foreach (var c in "password".ToCharArray())
                cxt.Credentials = new SharePointOnlineCredentials("username", password);
                    int pos = relativeURL.LastIndexOf("/") + 1;
                    var fileRef = relativeURL;
                    var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(cxt, fileRef);
                    var fileName = relativeURL.Substring(pos, relativeURL.Length - pos);
                    using (var fileStream = new System.IO.MemoryStream())
                        int extpos = fileName.LastIndexOf(".") + 1;
                        StreamToFileAttachment(fileStream, fileName);
            void StreamToFileAttachment(Stream str, string fileName)
                byte[] byteBuffer = new byte[str.Length];  
                str.Position = 0;
                           Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                Response.AddHeader("Content-Length", str.Length.ToString());
                Response.ContentType = "application/octet-stream";
                int len = 0;
                while ((len = str.Read(byteBuffer, 0, byteBuffer.Length)) > 0)


Using above code we can download SharePoint Document without actually sharing document with the end user.

Written by

Team Member


Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.

Want to streamline your business processes?

  • This field is for validation purposes and should be left unchanged.

Recent Articles

  • Managing mailbox through Email Archiving

    20 March’ 2018

    Introduction: Email can fill your Outlook Inbox quickly – new messages, replies, and forwards. Before you know it, yo...

    Read more
  • Workaround to Report.SAVEASPDF in NAV 2018

    20 March’ 2018

    Objective: In NAV 2017 Emailing the PDF by running the report using Report.SAVEASPDF is now not allowed in NAV 2018. Th...

    Read more
  • Dynamics 365 Client Diagnostics

    15 March’ 2018

    Main cause of Performance Issues: Bandwidth and latency are the primary characteristics which affects the performance o...

    Read more
  • Closing Blind Shift in MPOS and CPOS in Dynamics 365 for Retail

    15 March’ 2018

    Manual For closing Blind shift in POS: Blind shifts terminate the currently ongoing shift and when logged in a new shif...

    Read more
  • Persistent Filters in the Power BI Service

    13 March’ 2018

    Introduction: The feature is finally release, and it is power BI has announced general availability of persistent filt...

    Read more