C# – Extracting folder/sub folder name from SharePoint document library URL

csharepoint-online

I'm newbie to Sharepoint and currently using Sharepoint Online. I'm in need of retrieving files under a sharepoint document library in C#.

We have couple of document library urls as follows:

  1. https://customer1.sharepoint.com/DocumentFolder/Forms/AllItems.aspx
  2. https://customer2.sharepoint.com/sites/sitename/DocumentFolder/SubFolder/Forms/AllItems.aspx

I need to extract DocumentFolder name in case of URL 1 above, and DocumentFolder/SubFolder name in case of URL 2

Using Sharepoint REST service, I then would like to list files under DocumentFolder :

http://site url/_api/web/GetFolderByServerRelativeUrl('/DocumentFolder')

The challenge I have is to extract the DocumentFolder for the above URLs, as I could not find any API/method call to extract the DocumentFolder. I could try regex on the url, but it'll be helpful, if there is a right way to extract the DocumentFolder/SubFolder, that will be helpful.

Best Answer

We can use CSOM C# with CAML query to achieve it, set the view as < View Scope='RecursiveAll'>, thus gets the documents from root folder and its sub folders.

string targetSiteURL = @"https://xxx.sharepoint.com/sites/sitename";

var login = "xxx@xxx.onmicrosoft.com";
var password = "xxx";

var securePassword = new SecureString();

foreach (char c in password)
{
    securePassword.AppendChar(c);
}
SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(login, securePassword);

ClientContext ctx = new ClientContext(targetSiteURL);
ctx.Credentials = onlineCredentials;

List list = ctx.Web.Lists.GetByTitle("Documents");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = @"<View Scope='RecursiveAll'><Query></Query></View>";
camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();

foreach (var item in listItems)
{
     if (item.FileSystemObjectType == FileSystemObjectType.File)
     {
         // This is a File
     }
     else if (item.FileSystemObjectType == FileSystemObjectType.Folder)
     {
         // This is a  Folder
     }
}

More information for your reference:

http://www.sharepointpals.com/post/How-to-Get-All-the-Files-within-a-Folder-using-CAML-Query-in-SharePoint-Office-365-using-C-CSOM

Related Topic