While Downloading the excel file from SharePoint getting The remote server returned an error: (403) Forbidden. in windows application c#

Ashok Kumar 221 Reputation points
2022-10-14T13:06:30.92+00:00

I want to download the excel from SharePoint and I have read this post for achieve my requirement and also I have read this for NetworkCredential domain once I get the basic knowledge on this task I have written the code and at the runtime I got

The remote server returned an error: (403) Forbidden.

for this I have read this post for understanding the error and I have changed the code but not working well.

This is my code:

   public void DownloadFilesFromSharePoint(string siteUrl, string siteFolderPath, string localTempLocation)  
           {  
     
               //string tempLocation = @"c:\Downloads\Sharepoint\";  
               string tempLocation = localTempLocation;  
               System.IO.DirectoryInfo di = new DirectoryInfo(tempLocation);  
               foreach (FileInfo file in di.GetFiles())  
               {  
                   file.Delete();  
               }  
               ClientContext ctx = new ClientContext(siteUrl);  
     
               SecureString passWord = new SecureString();  
               foreach (char c in "Welcome@1045".ToCharArray()) passWord.AppendChar(c);  
     
               //"smtp.office365.com"; // "domain-com.mail.protection.outlook.com"; // "smtp.office365.com";//.secureserver.net";// "relay -hosting.secureserver.net"; //smtp-mail.outlook.com  
               //ctx.Credentials = new NetworkCredential("******@xxxx.com", "Welcome@1045", "smtp.office365.com");  
               ctx.Credentials = new NetworkCredential("******@xxxx.com", passWord);  
     
               FileCollection files = ctx.Web.GetFolderByServerRelativeUrl(siteFolderPath).Files;  
     
               ctx.Load(files);  
               if (ctx.HasPendingRequest)  
               {  
                   ctx.ExecuteQuery(); //The remote server returned an error: (403) Forbidden.(here I'm getting the error)  
               }  
     
               foreach (File file in files)  
               {  
                   FileInformation fileInfo = File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);  
                   ctx.ExecuteQuery();  
     
                   var filePath = localTempLocation + "\\" + file.Name;  
                   System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);  
     
                   fileInfo.Stream.CopyTo(fileStream);  
     
               }  
           }  

And I'm calling this method like this:

   string url ="https://xxxxx.sharepoint.com/sites/my_files/all%20Files";  
   string folderpath = "https://xxxxx.sharepoint.com/sites/my_files/all%20Files/Task%20Management";  
   string templocation = @"c:\Downloads\Sharepoint\";  
   DownloadFilesFromSharePoint(url, folderpath, templocation);  

And used this Microsoft.SharePoint.client dll.

Using Namespaces:

   using System;  
   using Form = System.Windows.Forms.Form;  
   using System.Security;  
   using System.IO;  
   using System.Net;  
   using Microsoft.SharePoint.Client;  
   using File = Microsoft.SharePoint.Client.File;  

For reference check this images

I have given the FolderPath correctly for reference https://xxxxx.sharepoint.com/sites/my_files/all%20Files and https://xxxxx.sharepoint.com/sites/my_files/all%20Files/Task%20Management this url links are getting the correct path of the folders.

Why this error is showing ?

Where I did the mistake and how to achieve this?

Help me on this.

Windows development Windows App SDK
Microsoft 365 and Office SharePoint For business Windows
Developer technologies C#
{count} votes

Accepted answer
  1. Tong Zhang_MSFT 9,251 Reputation points
    2022-10-17T06:11:51.96+00:00

    Hi @Ashok Kumar ,

    Per my test, when I use the code you provided (and the code in the article you provided), I get the same error: (403) Forbidden. According to my research and testing, the problem appeared on the connect to SharePoint. Please replace ctx.Credentials = new NetworkCredential("******@xxxx.com", passWord); in your code with ctx. Credentials = new SharePointOnlineCredentials(userName, password);.

    Here is my code , you can refer to :

    static void DownloadFilesFromSharePoint(string siteUrl, string siteFolderPath, string localTempLocation)  
            {  
                string userName = "******@xxxx.onmicrosoft.com";  
                Console.WriteLine("Enter your password.");  
                SecureString password = GetPassword();  
                var ctx =  new ClientContext(siteUrl);  
                ctx.Credentials = new SharePointOnlineCredentials(userName, password);  
      
                FileCollection files = ctx.Web.GetFolderByServerRelativeUrl(siteFolderPath).Files;  
      
                ctx.Load(files);  
                if (ctx.HasPendingRequest)  
                {  
                    ctx.ExecuteQuery();  
                }  
      
                foreach (File file in files)  
                {  
                    FileInformation fileInfo = File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);  
                    ctx.ExecuteQuery();  
      
                    var filePath = localTempLocation + "\\" + file.Name;  
                    System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);  
      
                    fileInfo.Stream.CopyTo(fileStream);  
      
                }  
            }  
            private static SecureString GetPassword()  
            {  
                ConsoleKeyInfo info;  
                //Get the user's password as a SecureString    
                SecureString securePassword = new SecureString();  
                do  
                {  
                    info = Console.ReadKey(true);  
                    if (info.Key != ConsoleKey.Enter)  
                    {  
                        securePassword.AppendChar(info.KeyChar);  
                    }  
                }  
                while (info.Key != ConsoleKey.Enter);  
                return securePassword;  
            }  
      
           static void Main(string[] args)  
            {  
                Program.DownloadFilesFromSharePoint("https://xxxx.sharepoint.com/sites/zellatest", "https://xxxx.sharepoint.com/sites/zellatest/test1/aaa", @"C:\Temp");  
            }  
    

    My test result:
    250955-image.png

    More information for reference: Connect To SharePoint 2013 Online Using CSOM With Console Application

    Hope it can help you. Thanks for your understanding and support.

    Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.