简体   繁体   中英

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 . 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.

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 )?

My current solution, removing segment by segment until the Uri is valid, but this is time consuming for client experience.

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))
{   

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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