Hi sorry for the delay.
Please see my working code below.
If you are using SharePoint online, use below code
public static ClientContext GetClientContext(string url)
{
SecureString securePassword = new SecureString();
ClientContext context = null;
try
{
using (context = new ClientContext(url))
{
foreach (char c in "Password") securePassword.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("user@tenent.onmicrosoft.com", securePassword);
context.Load(context.Web, w => w.ServerRelativeUrl, w => w.Url);
context.ExecuteQuery();
}
}
catch (Exception ex)
{
}
return context;
}
If you are using SharePoint on premises server, you can get the context in two ways. Using app pool account or by passing your user creds. Below code using the default app pool credentials.
string parentSiteUrl = Helper.GetParentWebUrl(siteUrl);
clientContext = new ClientContext(parentSiteUrl);
clientContext.Credentials = CredentialCache.DefaultCredentials;
clientContext.Load(clientContext.Web, w => w.Url, w => w.Lists, w => w.ServerRelativeUrl, w => w.Title, w => w.SiteGroups);
clientContext.ExecuteQuery();
Or you can pass your credentials as below.
var clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new NetworkCredential("domain\\user", "password");
clientContext.Load(clientContext.Web, w => w.Lists);
clientContext.ExecuteQuery();
Let me know if you have any queries.