-1

Good day all,

I'm working with c# and the SharePoint CSOM for SharePoint Online. My code works with files in a specific library where I loop through a collection of File object: foreach (Microsoft.SharePoint.Client.File xFile in ParentFolder.Files) { ....

I'm not able to initialize the ServerRelativePath property.

            foreach (Microsoft.SharePoint.Client.File xFile in ParentFolder.Files)
            {
                Console.WriteLine(xFile.Name);

                //xFile.Context.Load(zzzzzz);
                xFile.Context.Load(xFile.ListItemAllFields);
                xFile.Context.Load(xFile.ModifiedBy);
                xFile.Context.ExecuteQuery();

                Console.WriteLine(xFile.ServerRelativePath);  //Error here

                More code ...

            }

The error I'm getting is the normal "The property or field 'ServerRelativePath' has not been initialized..."

However, I'm not able to load anything into the context that allows me to get past this error.

What am I missing?

Many thanks Christoff

1 Answers1

1

I found the solution:

First mistake was trying to Load the RelativePath at the wrong place. In my code in the original post, I try to load the property while working with a specific file.

It seems the correct place was with the previous context load where I actually get the collection of files to loop through.

        ParentFolder.Context.Load(ParentFolder);
        ParentFolder.Context.Load(ParentFolder.Folders);
        ParentFolder.Context.Load(ParentFolder.Files);
 I was missing this     >>>>          ParentFolder.Context.Load(ParentFolder.Files, items => items.Include(item => item.ServerRelativePath));
        ParentFolder.Context.ExecuteQuery();

So the correct code looks like this:

        ParentFolder.Context.Load(ParentFolder);
        ParentFolder.Context.Load(ParentFolder.Folders);
        ParentFolder.Context.Load(ParentFolder.Files);
        ParentFolder.Context.Load(ParentFolder.Files, items => items.Include(item => item.ServerRelativePath));
        ParentFolder.Context.ExecuteQuery();


        if (Applicable business logic){

            foreach (Microsoft.SharePoint.Client.File xFile in ParentFolder.Files){

                FileCounter++;
                Console.WriteLine(xFile.Name + "  (" + xFile.ServerRelativePath.DecodedUrl + ")");

                xFile.Context.Load(xFile.ListItemAllFields);
                xFile.Context.Load(xFile.ModifiedBy);
                xFile.Context.ExecuteQuery();


                More business logic code relating to the file itself...


        }  //end if statement
     }  // end foreach loop