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:
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.