将 Powershell Connect-PnPOnline 转换为 C#

Convert Powershell Connect-PnPOnline to C#

寻找如何将大量用于共享点 PnP 的 powershell 转换为 C#

示例:Connect-PnPOnline

一些 Powershell

$PasswordAsSecure = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential ($UserName , $PasswordAsSecure)
Connect-PnPOnline -Url $SiteUrl -Credentials $Credentials
$RootSiteContext = Get-PnPContext

# Determine the SharePoint version
$ServerVersion = (Get-PnPContext).ServerLibraryVersion.Major

这要在 C# 应用程序中吗?

这里有一些比 "works" 更具体的 powershell,但是 github 示例库没有那么有用。

                    Connect-PnPOnline -Url $hubUrl -Credentials $O365Credentials
                    $sc = Get-PnPSite
                    $w = Get-PnPWeb
                    $baseRelUrl=$w.ServerRelativeUrl
                    if (-not $baseRelUrl ) {
                          throw "hub site isn't created"
                    }

PnP PowerShell 在幕后包裹了很多东西,让您轻松使用。

要将代码修改为C#,需要按如下方式编写:

var siteUrl = "https://your-sitecollection-url";
var userName = "userName";
var password = "password";

using (ClientContext clientContext = new ClientContext(siteUrl))
{
    SecureString securePassword = new SecureString();
    foreach (char c in password.ToCharArray())
    {
        securePassword.AppendChar(c);
    }

    clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
    clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);

    clientContext.ExecuteQuery();

    var ServerVersion = clientContext.ServerLibraryVersion.Major;

    var site = clientContext.Site;
    var web = clientContext.Site.RootWeb;

    clientContext.Load(web, w => w.ServerRelativeUrl);
    clientContext.ExecuteQuery();

    var serverRelativeUrl = clientContext.Site.RootWeb.ServerRelativeUrl;
}

要执行此代码,您的项目中需要 Microsoft.SharePointOnline.CSOM nuget 包。