Search code examples
c#asp.netsharepointsharepoint-2016

SharePoint Login Credential


Currently I try to developed application by using SharePoint that retrieve data from List

Now I try to developed for Login Function, The error display as Below

The underlying connection was closed: An unexpected error occurred on a send.

Here with my Source Code

string WebUrl = "https://xxx.sharepoint.com/sites/devspace";
            string username = txtUsername.Text;
            string pwd = txtPassword.Text;

            ClientContext context = new ClientContext(WebUrl);
            Web web = context.Web;

            SecureString passWord = new SecureString();
            foreach (char c in pwd.ToCharArray())
                passWord.AppendChar(c);
            context.Credentials = new SharePointOnlineCredentials(username, passWord);
            try
            {
                context.Load(web);
                context.ExecuteQuery();
                lblStatus.Text = "Olla " + web.Title;

            }catch(Exception ex)
            {
                lblStatus.Text = ex.Message.ToString();
            }

Any suggestion for this? Thank in advanced.

Updated:

I'm using SharePoint 2016, login via Windows Server AD.


Solution

  • As discussed, you are using SharePoint 2016, then please download and install CSOM with SharePoint 2016 version Nuget package not SharePoint Online:

    Microsoft.SharePoint2016.CSOM

    And use this code snippet:

          ClientContext clientContext = new ClientContext("https://example.com/sites/testsite/");  
          clientContext.Credentials = new NetworkCredential("user", "password", "domain");
                // Get the SharePoint web  
                Web web = clientContext.Web;  
    
                // Get the SharePoint list collection for the web  
                ListCollection listColl = web.Lists;  
    
                // Retrieve the list collection properties  
                clientContext.Load(listColl);  
    
                // Execute the query to the server.  
                clientContext.ExecuteQuery();  
    
                // Loop through all the list  
                foreach (List list in listColl)  
                {  
                    // Display the list title and ID  
                    Console.WriteLine("List Name: " + list.Title + "; ID: " + list.Id);  
                }  
                Console.ReadLine();
    

    SharePoint 2016 On Premise not need to use SharePointOnlineCredentials class, just pass username, password, domain as code snippet above.