0
votes

In my first outing with csom and the document library, I encountered a difficult error when attempting to access a document library object property as file.File.Title using the following code.

The error is

 Object reference not set to an instance of an object on server.

The code shown is what "works" for my exercise.

What step am I missing to be able to use file.File.Title instead of file.FieldValues["Title"].

The code snippet is a very primitive attempt to get a list of files in the default Document library folder. In a following iteration, I need to update the caml to retrieve a specific file.

        var lib = ctx.Web.DefaultDocumentLibrary();
        ctx.Load(lib);
        ctx.ExecuteQuery();

        var files = lib.GetItems(CreateAllFilesQuery());
        ctx.Load(files);
        ctx.Load(files, items => items.Include( item => item.File.Title ));
        ctx.ExecuteQuery();

        foreach(var file in files )
        {
            if(!(file.FieldValues["Title"] == null) )
            {
                string FileName = file.FieldValues["Title"].ToString();
                if (FileName == DocumentName)
                    return true;
            }
        }

    public static CamlQuery CreateAllFilesQuery()
    {
        var qry = new CamlQuery();
        qry.ViewXml = @"<View Scope=\'FilesOnly\'>
            <Query></Query>
            <ViewFields>
               <FieldRef Name='Title'  />
               <FieldRef Name='ContentType' />
               <FieldRef Name='DocIcon' />
            </ViewFields>
        </View>";
        return qry;
    }
1

1 Answers

0
votes

After further research, I discovered that my caml query was at fault. The syntax error was placing slashes around the Scope value. The corrected query allows me to reference file.File.Title as expected. The additional benefit is that I am only getting back files rather than files and folders.

qry.ViewXml = @"<View Scope='FilesOnly'>
    <Query></Query>
    <ViewFields>
       <FieldRef Name='Title'  />
       <FieldRef Name='ContentType' />
       <FieldRef Name='DocIcon' />
    </ViewFields>
</View>";