Below is a sample code using Client-Side Object Model (CSOM) to connect to SharePoint Online Site using Visual Studio. We are just fetching the Title and URL of the site. Below are the steps:
-
- Open Visual Studio. Select a Console Application. You can also use Forms Application for this program.
- Add Microsoft.SharePointOnline.CSOM as a Reference using NuGet Packages.
- Write the following code in the Programs.cs file.
class Program
{
static void Main(string[] args)
{
string username = "YourUserName";
string siteURL="YourSiteURL";
Console.WriteLine("Enter your password: ");
SecureString password = GetPassword();
GetAllWebProperties(siteURL, username, password);
}
public static void GetAllWebProperties(string siteURL, string username, SecureString password)
{
using (var context = new ClientContext(siteURL))
{
context.Credentials = new SharePointOnlineCredentials(username, password);
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
Console.ReadLine();
}
}
public static SecureString GetPassword()
{
ConsoleKeyInfo info;
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;
}
}
This will ask you to enter the password. Enter the password that you use to access your Site Collection.
You will get the below output.
![]()