简体   繁体   English

如何为 ClientContext 正确删除 SitePages/Home.aspx 或 Forms/AllItems.aspx?

[英]How do I remove SitePages/Home.aspx or Forms/AllItems.aspx correctly for ClientContext?

I am using CSOM to connect to SharePoint and load files from Document Libraries .我正在使用 CSOM 连接到 SharePoint 并从Document Libraries加载文件。 My problem is when I create ClientContext object with the full URL that ends with Forms/AllItems.aspx or SitePages/Home.aspx or other bits, it will throw invalid URL exception.我的问题是,当我使用以Forms/AllItems.aspxSitePages/Home.aspx或其他位结尾的完整 URL 创建ClientContext对象时,它会抛出无效的 URL 异常。

For example, this will work:例如,这将起作用:

ClientContext ctx = new ClientContext("https://mycompany.sharepoint.com/Extranet/Test%20AutoAppraisal");

And this will not work:这将不起作用:

ClientContext ctx = new ClientContext("https://mycompany.sharepoint.com/Extranet/Test%20AutoAppraisal/SitePages/Home.aspx");

Is there a safe way to trim SharePoint URL similar to this new Microsoft Flow feature ( Automatic trimming of SharePoint URLs )?是否有一种安全的方法来修剪与此新 Microsoft Flow 功能( SharePoint URL 的自动修剪)类似的 SharePoint URL

My current solution, removing segment by segment until the Uri is valid, but this is time consuming for client experience.我目前的解决方案是Uri删除,直到Uri有效,但这对于客户体验来说很耗时。

private static Uri TryResolvingUrl(Uri path)
{
    string host = null;
    while (true)
    {
        try
        {
            ClientContext ctx = new ClientContext(path)
            {
                Credentials = _credential,
                RequestTimeout = -1
            };

            ctx.Load(ctx.Web, web => web.ServerRelativeUrl);
            ctx.ExecuteQueryRetry();
            return path;
        }
        catch (Exception e)
        {
            if (host == null)
            {
                host = path.Scheme + "://" + path.Authority;
            }

            if (path.Segments.Length == 1)
            {
                throw e; // we wont be able to use this url!
            }

            string newUrl = host;
            for (int i = 0; i < path.Segments.Length - 1; i++)
            {
                newUrl += path.Segments[i];
            }

            path = new Uri(newUrl.Unescape());
         }
    }
}

The following code snippet for your reference.以下代码片段供您参考。

string siteUrl = "https://mycompany.sharepoint.com/Extranet/Test%20AutoAppraisal/Account%20Managemenet%20Archive/Forms/AllItems.aspx";       
var urlArray = siteUrl.Split('/');
siteUrl = urlArray[0]+"//"+urlArray[2]+"/"+urlArray[3]+"/"+urlArray[4];

using (ClientContext ctx = new ClientContext(siteUrl))
{   

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM