Quantcast
Channel: SharePoint 2013 - Development and Programming forum
Viewing all articles
Browse latest Browse all 7589

Using SharePoint Online (365) CSOM Receiving 401 Unauthorized

$
0
0

Hello All

I'm trying to download from a document library to a network share using .NET and the CSOM package.  When running the code, I'm receiving System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.'

Here is the call to my local method.

DownloadFilesFromSharePoint(@"http://site.sharepoint.com/sites/SubSite", @"https://site.sharepoint.com/sites/SubSite/Shared%20Documents/Subfolder", @"X:\MyDestination");

The below code fails at ctx.ExecuteQuery();

internal static void DownloadFilesFromSharePoint(string siteUrl, string folderPath, string tempLocation)
        {
            var Username = "me@site.com";
            var Password = "Password01"; //changing password for question
            var securePassword = new SecureString();
            //Convert string to secure string
            foreach (char c in Password)
            {
                securePassword.AppendChar(c);
            }
            securePassword.MakeReadOnly();


            ClientContext ctx = new ClientContext(siteUrl);
            
            ctx.Credentials = new SharePointOnlineCredentials(Username, securePassword);

            FileCollection files = ctx.Web.GetFolderByServerRelativeUrl(folderPath).Files;

            ctx.Load(files);
            ctx.ExecuteQuery();

            foreach (Microsoft.SharePoint.Client.File file in files)
            {
                FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);
                ctx.ExecuteQuery();

                var filePath = tempLocation + file.Name;
                using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
                {
                    fileInfo.Stream.CopyTo(fileStream);
                }
            }
        }

Do I need some type of elevated permissions?


Viewing all articles
Browse latest Browse all 7589

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>