sharepointcsomo365rwsclient

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


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?


Solution

  • static public string ReturnFileParentUrl(string url)
            {
                try
                {
                    Uri uri = new Uri("https://XXX.sharepoint.com/");
                    using (var ctx = GetContext(uri, "YYY@DOMAIN.com", "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;
            }