I have initialized a general list and I want to save all Files and Folders from Sharepoint.
List<object> filesAndFolders = new List<object>();
I have loaded all files and folders from SharePoint and added them to the list and now I want to access FieldValues, but when I try to iterate through the list I can't access the file or folder because is being saved as an object{Microsoft.Sharepoint.Client.File} or Folder.
foreach(var item in filesAndFolders){
//getFiledValues here
item.ListItemAllFields.FiledValues ..
}
I have an error saying that item.ListItemAllFields.FiledValues doesn't exist. How can I solve this and be able to save Files and Folders in one List? Thank you!
CodePudding user response:
You can check the type of object at run-time like this:
List<object> filesAndFolders = new List<object>();
foreach (var item in filesAndFolders)
{
if (item is Microsoft.Sharepoint.Client.File)
{
var fileItem = item as Microsoft.Sharepoint.Client.File;
// do stuff with fileItem
}
else if (item is Microsoft.Sharepoint.Client.Folder)
{
var folderItem = item as Microsoft.Sharepoint.Client.Folder;
// do stuff with folderItem
}
else
{
// Oops, some other object type
}
}
Althogh I can't access @Fildor's fiddle due to company firewall, I believe he or she is suggesting one of the following more compact forms:
foreach (var item in filesAndFolders)
{
if (item is Microsoft.Sharepoint.Client.File fileItem)
{
// do stuff with fileItem
}
else if (item is Microsoft.Sharepoint.Client.Folder folderItem)
{
// do stuff with folderItem
}
else
{
// Oops, some other object type
}
}
or this
foreach (var item in filesAndFolders)
{
switch (item)
{
case File fileItem:
// do stuff with fileItem
break;
case Folder folderItem:
// do stuff with folderItem
break;
default:
// Oops, some other object type
break;
}
}
which became possible in c# version 7.0.
CodePudding user response:
Use the ClientObject as a type in your list.
using Microsoft.SharePoint.Client.ClientObject;
List<ClientObject> filesAndFolders = new List<ClientObject>();
foreach(var item in filesAndFolders){
//getFiledValues here
}