1

I have a requirement where i need to download excel file from Office 365 Share Point site through my windows application using C#. This is how my site looks https://microsoft.sharepoint.com/teams/********/BISD%20Tier%203%20Team%20Documents/Forms/AllItems.aspx Below are my constraints.

  • I am the user who have the access to the files, I am not admin.
  • My application will run in a non share point environment.

Previously I have implemented the same functionality using List.asmx but the site is not secured one looks like this http://*********/sites/sandbox/Salesanalytics/_layouts/15/start.aspx#/. When i tried the same approach i am getting error message User doesn't have permissions. Please suggest the approach for my requirement. List.asmx sample to download excel file

2 Answers 2

1

Sample on using List.asmx on SharePoint Online below, it is console application, but you can extract the essential parts and merge with your code, especially the authentication part: ClaimClientContext.GetAuthenticatedContext (see here for the class)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using System.Net;
using MSDN.Samples.ClaimsAuth;
namespace Sp_Ctx
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            //if (args.Length < 1) { Console.WriteLine("SP_Ctx <url>"); return; }
            //string targetSite = args[0];
            string targetSite = "https://sharepointOnlineURLRoot/sites/siteName";
            using (ClientContext ctx = ClaimClientContext.GetAuthenticatedContext(targetSite))
            {
                if (ctx != null)
                {
                    ctx.Load(ctx.Web); // Query for Web
                    ctx.ExecuteQuery(); // Execute
                    Console.WriteLine(ctx.Web.Title);
                }  
            }
            Console.WriteLine("");
            Console.WriteLine("");
            CookieCollection authCookie = 
                ClaimClientContext.GetAuthenticatedCookies(targetSite, 925, 525);
            listWS.Lists list = new listWS.Lists();
            list.Url = "https://sharepointOnlineURLRoot/sites/siteName/_vti_bin/Lists.asmx"
            //list.Timeout = 15000; //in milliseconds
            list.CookieContainer = new CookieContainer();
            list.CookieContainer.Add(authCookie);
            string listName = "Shared Documents";
            string viewName = "";
            //string listName = "{1A4A3C5D-360E-45EB-B9ED-E8653981CAC0}";
            //string viewName = "{5A4AF2C5-8A9F-427F-B8AA-BC59E3BE8AA0}";
            string rowLimit = "5";
            // Instantiate an XmlDocument object         
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
            System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
            System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");

            //*Use CAML query*/        
            query.InnerXml = "<Where><Gt><FieldRef Name=\"ID\" />" + 
                "<Value Type=\"Counter\">0</Value></Gt></Where>";
            viewFields.InnerXml = "<FieldRef Name=\"Title\" />";
            //queryOptions.InnerXml = "";
            queryOptions.InnerXml = 
                "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" + 
                "<DateInUtc>TRUE</DateInUtc>";
            System.Xml.XmlNode nodes = 
                list.GetListItems(
                    listName, 
                    viewName, 
                    query, 
                    viewFields, 
                    rowLimit, 
                    null, 
                    string.Empty);
            string ixml = list.GetList(listName).InnerXml;
            Console.WriteLine(
                "Retrieving title of all the items in SharePoint Online" +
                 "sites 'Shared Documents' using Lists webservice");
            Console.WriteLine(
                "===========================================" +
                "=============================================");
            foreach (System.Xml.XmlNode node in nodes)
            {
                if (node.Name == "rs:data")
                {
                    for (int i = 0; i < node.ChildNodes.Count; i++)
                    {
                        if (node.ChildNodes[i].Name == "z:row")
                        {
                            Console.WriteLine(
                                node.ChildNodes[i].Attributes["ows_Title"].Value);
                        }
                    }
                }
            }
            Console.ReadLine();
        }
    }
}

Source

2
1

Since SharePoint 2013/Online supports a different client APIs there are several options to download a file from SharePoint depending on the API:

About SharePoint Online authentication

I guess your main concern is authentication in SPO. SharePoint Online (SPO) uses claims-based authentication mode. Microsoft released SharePoint Server 2013 Client Components SDK which contains SharePointOnlineCredentials class, below are provided some example that demonstrate how to utilize that class.

The following example demonstrates how to download a file from SPO using WebClient Class:

  using (var client = new WebClient())
  {
      client.Credentials = GetSPOCredentials(webUri, userName, password);
      client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
      client.DownloadFile(sharePointFileUrl, localFileName);
  }  

where

public static SharePointOnlineCredentials GetSPOCredentials(Uri webUri, string userName, string password)
{
     var securePassword = new SecureString();
     foreach (var ch in password) securePassword.AppendChar(ch);
     return new SharePointOnlineCredentials(userName, securePassword);
}

The following example demonstrates how to authenticate SharePoint Online Web Services:

using(var proxyLists = new Lists())
{
     proxyLists.Url = webUri + "/_vti_bin/Lists.asmx";
     proxyLists.CookieContainer = GetAuthCookies(webUri, userName, password);
     //...
 }

where

private static CookieContainer GetAuthCookies(Uri webUri, string userName, string password)
{
    var securePassword = new SecureString();
    foreach (var c in password) { securePassword.AppendChar(c); }
    var credentials = new SharePointOnlineCredentials(userName, securePassword);
    var authCookie = credentials.GetAuthenticationCookie(webUri);
    var cookieContainer = new CookieContainer();
    cookieContainer.SetCookies(webUri, authCookie);
    return cookieContainer;
}

How to download a file using CSOM

SharePoint CSOM API contains File.OpenBinaryDirect method that is intended for downloading a file from SharePoint:

private static void DownloadFile(Web web, string fileUrl,string targetPath)
{
    var ctx = (ClientContext)web.Context;
    ctx.ExecuteQuery();
    using(var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileUrl))
    {
         var fileName = Path.Combine(targetPath, System.IO.Path.GetFileName(fileUrl));
         using (var fileStream = System.IO.File.Create(fileName))
         {
             fileInfo.Stream.CopyTo(fileStream);
         }
    }
}

Usage

using (var ctx = GetSPOContext(webUri,userName,password))
{
      var web = ctx.Web;
      DownloadFile(web, "/documents/SharePoint User Guide 2013.docx", @"c:\downloads");
}

where

public static ClientContext GetSPOContext(Uri webUri, string userName, string password)
{
     var securePassword = new SecureString();
     foreach (var ch in password) securePassword.AppendChar(ch);
     return new ClientContext(webUri) { Credentials = new SharePointOnlineCredentials(userName, securePassword) };
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.