Search code examples
c#sharepointsharepoint-clientobject

SharePoint item.File - ServerObjectNullReferenceException


I'm attempting to load information about all File Items in a list. In this snippet, item refers to a ListItem

switch(item.FileSystemObjectType)
            {
                case FileSystemObjectType.File:
                    if (ListOptions.IndexFileItems)
                    {
                        ClientContext.Load(item, i => i.File);
                        ClientContext.ExecuteQuery();
                        if (item.File.Exists)

When the code is run, it reaches the final line and then throws ServerObjectNullReferenceException.

I do not understand this, as the item has declared itself to be of Type File in it's FileSystemObjectType, should I not expect the Fileproperty to have a reference, having loaded it? Am I loading the file incorrectly?


Solution

  • ListItem.File is used in document library, please make sure list object is a library:

    ListItem.File property

    I tested the code snippet below, work as expected:

                ClientContext ctx = new ClientContext("http://sp/sites/dev/");
                List list = ctx.Web.Lists.GetByTitle("dccc");
                CamlQuery caml = new CamlQuery();
                ListItemCollection items = list.GetItems(caml);
                ctx.Load(items);
                ctx.ExecuteQuery();
                foreach (ListItem item in items)
                {
    
                    switch (item.FileSystemObjectType)
                    {
                        case FileSystemObjectType.File:
                            ctx.Load(item, i => i.File);
                            ctx.ExecuteQuery();
                            if (item.File.Exists)
                            {
                                Console.WriteLine(item.File.Name);
                            }
                            break;
                    }
                }
    

    enter image description here

    So the files are two jpg file:

    enter image description here