(401) Unauthorized SharePoint - C# Console Application Code
-
09-10-2020 - |
Question
Unable to upload the documents in SharePoint Online using a console application. Any solution to this problem?
public static void SaveFileToSharePoint(string fileName)
{
string Url = "https://xxxxx.sharepoint.com/sites";
string libraryName = "Shared Documents";
using (ClientContext clientContext = new ClientContext(Url))
{
SecureString passWord = new SecureString();
foreach (char c in "*****".ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials("xxxx@xxxgmail.onmicrosoft.com",
passWord);
List list = clientContext.Web.Lists.GetByTitle(libraryName);
clientContext.Load(list.RootFolder);
clientContext.ExecuteQuery();
using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, list.RootFolder.ServerRelativeUrl.ToString() + "/" + fileName.Split('\\')[1], fileStream, true);
}
}
}
Solution
You should refer this link once. This post contains the code for authenticating with your SharePoint Online and upload a file into the given library.
class Program
{
static void Main(string[] args)
{
using (ClientContext clientContext = new ClientContext("https://xxxx.sharepoint.com/sites/SiteName"))
{
SecureString passWord = new SecureString();
foreach (char c in "YourPassword".ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials("username@domain.onmicrosoft.com", passWord);
Web web = clientContext.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(@"C:\Applications\PropertyMaster.xlsx"); // this is my sample file path
newFile.Url = "testFile.xlsx"; // file name which should be created in library
List docs = web.Lists.GetByTitle("Library Name");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
clientContext.ExecuteQuery();
}
}
}
The above code worked for me.
I have created a console application. Still you have any issue then inform me.
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange