How to Check Use SharePointOnlineCredentials for SharePoint Online and NetworkCredential in other case. - Song Nghia - Technical Consultant

Dynamic 365 FO Dynamic 365 Retail

Thứ Ba, 28 tháng 5, 2019

How to Check Use SharePointOnlineCredentials for SharePoint Online and NetworkCredential in other case.

How to Check Use SharePointOnlineCredentials for SharePoint Online and NetworkCredential in other case.


Song Nghia - Technical Consultant

var siteUrl = "https://sharepointsiteurl";
// Login
var userLogin = "userLogin@domain";
// Password
var userPassword = "P@ssw0rd";

var pwd = new SecureString();
foreach (var c in userPassword) pwd.AppendChar(c);
var SPOCredentials = new SharePointOnlineCredentials(userLogin, pwd);
var SPCredentials = new NetworkCredential(userLogin, pwd);

using (var ctx = new ClientContext(siteUrl))
{
    try
    {
        // try to use SharePoint Online Credentials
        ctx.Credentials = SPOCredentials;
        ctx.ExecuteQuery();
    }
    catch (ClientRequestException)
    {
        // switch to NetworkCredential
        ctx.Credentials = SPCredentials;
        ctx.ExecuteQuery();
    }
    catch (NotSupportedException)
    {
        // switch to NetworkCredential
        ctx.Credentials = SPCredentials;
        ctx.ExecuteQuery();
        Console.WriteLine("SharePoint On-premise");
    }

    // Working with SharePoint Data
}