Master_T
Master_T

Reputation: 7943

Cannot list files/folders with the SharePoint Client API

I'm trying to use the official SharePoint Client library in C# (Microsoft.SharePoint.Client) to list files and folders in a SharePoint online site.

This is how the site files look:

enter image description here

Based on the URL (you can see it in the image), this is how I'm trying to do it:

using (ClientContext ctx = new ClientContext("https://*******.sharepoint.com/sites/cms"))
{
    //Setup authentication
    SecureString passWord = new SecureString();
    foreach (char c in "mypassword".ToCharArray())
    {
        passWord.AppendChar(c);
    }

    //Connect
    ctx.Credentials = new SharePointOnlineCredentials("myuser", passWord);
    Web web = ctx.Web;

    //Retrieve folder
    var folder = web.GetFolderByServerRelativeUrl("/doc/projects/C07725");
    ctx.Load(folder);
    ctx.ExecuteQuery(); //This seems to work

    //List subfolders
    ctx.Load(folder.Folders);
    ctx.ExecuteQuery(); //This throws Microsoft.SharePoint.Client.ServerException: 'File Not Found.'
}

However the last line, as shown in the comment, throws

Microsoft.SharePoint.Client.ServerException: 'File Not Found.'

This also happens if I try with the Files property, instead of Folders.

What am I missing here? The folder variable seems to get loaded correctly (the ItemsCount property inside it is set to 11 after calling the first .ExecuteQuery()), but I cannot get any further without raising an exception. What am I doing wrong here?

Upvotes: 1

Views: 1351

Answers (1)

Master_T
Master_T

Reputation: 7943

Well, I found out the problem.

It was indeed a problem with where I "split" the path.

I had to go further with the site URL:

using (ClientContext ctx = new ClientContext("https://*******.sharepoint.com/sites/cms/doc/projects"))

and remove that part from the folder path:

var folder = web.GetFolderByServerRelativeUrl("C07725");

now it works correctly.

Upvotes: 1

Related Questions