SharePoint online (O365):How to get a parent item URL?

1.1k views Asked by At

Having the following URL

https://test.sharepoint.com/shared%20documents/MyFolder1/myImg1.jpeg

I need to send a request for parent URL of this item (in this specific case image) and to get a response:

https://test.sharepoint.com/shared%20documents/MyFolder1/

Does such a request exists if using a CSOM or Office 365 Activity API? Where in documentation can i find such examples?

1

There are 1 answers

0
Natalie Polishuk On BEST ANSWER
static public string ReturnFileParentUrl(string url)
        {
            try
            {
                Uri uri = new Uri("https://XXX.sharepoint.com/");
                using (var ctx = GetContext(uri, "[email protected]", "password"))
                {

                    Microsoft.SharePoint.Client.File item = ctx.Web.GetFileByServerRelativeUrl(url);

                    ctx.Load(item);
                    ctx.ExecuteQuery();

                    Console.WriteLine("file: {0}\n", item.Name);
                    Console.WriteLine("Type: {0}\n", item.TypedObject.ToString());
                    if (item.TypedObject.ToString() == "Microsoft.SharePoint.Client.File") //To check if there is a better way to check if the item is a file 
                        if (item.ServerObjectIsNull != true)
                        {
                            ctx.Load(item, i => i.ListItemAllFields);
                            ctx.ExecuteQuery();
                            var folder = ctx.Web.GetFolderByServerRelativeUrl((string)item.ListItemAllFields["FileDirRef"]);
                            ctx.Load(folder);
                            ctx.ExecuteQuery();
                            Console.WriteLine("parent relative url {0}\n", folder.ServerRelativeUrl);
                            return folder.ServerRelativeUrl;
                        }

                    return null;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return null;
        }