I have a sharepoint location where the total number of files are more than 5000. In this case I am not able to view them in file explorer. Is there any other option to retrieve the files available in sharepoint programatically and not using sharepoint website
You can index the column and use below code :
$list = $ctx.Web.Lists.GetByTitle($DocLibName)
$ctx.Load($list)
$ctx.ExecuteQuery()
## View XML
$qCommand = #"
<View Scope="RecursiveAll">
<Query>
<OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
</Query>
<RowLimit Paged="TRUE">5000</RowLimit>
</View>
"#
## Page Position
$position = $null
## All Items
$allItems = #()
Do{
$camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
$camlQuery.ListItemCollectionPosition = $position
$camlQuery.ViewXml = $qCommand
## Executing the query
$currentCollection = $list.GetItems($camlQuery)
$ctx.Load($currentCollection)
$ctx.ExecuteQuery()
## Getting the position of the previous page
$position = $currentCollection.ListItemCollectionPosition
# Adding current collection to the allItems collection
$allItems += $currentCollection
}
# the position of the last page will be Null
Until($position -eq $null)
This code is resembling the pagination behaviour.
$position will the previous page index.
Hope this helps.
You could refer to the code in this post:
https://sharepoint.stackexchange.com/questions/128373/large-list-issue-with-csom
Note: you have to use indexed column in the camel query.
ClientContext clientContext = new ClientContext("weburl");
List list = clientContext.Web.Lists.GetByTitle("ListTitle");
ListItemCollectionPosition position = null;
do
{
CamlQuery camlQuery = new CamlQuery();
camlQuery.ListItemCollectionPosition = position;
camlQuery.ViewXml = #"<View>
<ViewFields>
<FieldRef Name='Title'/>
</ViewFields>
<RowLimit>5000</RowLimit>
</View>";
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
position = listItems.ListItemCollectionPosition;
foreach (ListItem listItem in listItems)
Console.WriteLine("Title: {0}", listItem["Title"]);
}
while(position != null)
Related
Is there a Sharepoint API to get entire content of files/folders for a particular folder at once ?
I don't want to use GetFolderByServerRelativePath recursively.
If don't want to use GetFolderByServerRelativePath, you can use CSOM with CAML Query like this:
string password = "pwd";
string account = "user#Tenant.onmicrosoft.com";
var secret = new SecureString();
foreach (char c in password)
{
secret.AppendChar(c);
}
using (ClientContext ctx = new ClientContext("https://Tenant.sharepoint.com/sites/sitename"))
{
ctx.Credentials = new SharePointOnlineCredentials(account,secret);
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
List list = web.Lists.GetByTitle("Documents");
ctx.Load(list);
ctx.ExecuteQuery();
Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + "/shared%20documents/");
ctx.Load(folder);
ctx.ExecuteQuery();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='RecursiveAll'>
<Query>
</Query>
</View>";
camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
ListItemCollection listItems = list.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
foreach (var item in listItems)
{
Console.WriteLine(item.FieldValues["FileRef"].ToString());
}
}
will return all folders/subfolders/files together, hopefully, this is what you need.
I have sharepoint list I have added a column "DistributionId" as a single line of text. I can see it in the fieldvalues when I debug. I can see it being set by the line listItem.FieldValues["DistributionId"] = "test";. However this is not updated in SharePoint and reverts to a blank value when the execute query is fired underneath. Also value is not set in SharePoint when checked directly. Any idea what I am doing wrong?
using (ClientContext clientContext = new ClientContext(SpEndPointUri))
{
Site site = clientContext.Site;
Web web = clientContext.Web;
List list = clientContext.Web.Lists.GetByTitle(library);
CamlQuery query = new CamlQuery();
query.ViewXml = #"<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + documentId + #"</Value></Eq></Where></Query></View>";
ListItemCollection items = list.GetItems(query);
// Retrieve all items in the ListItemCollection from List.GetItems(Query).
clientContext.Load(items, ic => ic.Include(i => i, i => i["DisplayName"], i => i["Id"], i => i["HasUniqueRoleAssignments"]));
clientContext.ExecuteQuery();
ListItem listItem = items[0];
clientContext.Load(listItem);
clientContext.ExecuteQuery();
listItem.FieldValues["DistributionId"] = "test";
listItem.Update();
clientContext.ExecuteQuery();
clientContext.Load(listItem);
clientContext.ExecuteQuery();
}
Use ListItem.Item property to set field value instead. ListItem.FieldValues property is used only for getting a collection of key/value pairs containing the names and values for the fields of the list item.
How to update ListItem field value:
var list = ctx.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(listItemId);
listItem[fieldName] = fieldValue;
listItem.Update();
ctx.ExecuteQuery();
I got the following error while running SharePoint ClientObject Model. I went through my code and checked if I missed any thing to load, but didn't see.
"Process is Terminated: The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."
I am not sure what I am missing after searching about this for a couple of hour.
The following is my code. Hope any one can help.
public static void UpdatePackageStatus(string Teamsite, string Libname, string Packagename, string User, string Password, string Domain, string PackageStatus, string DeploymentSucceeded, string query)
{
using(clientOM.ClientContext Ctx = new clientOM.ClientContext(Teamsite))
{
Ctx.Credentials = new System.Net.NetworkCredential(User, Password, Domain);
clientOM.Web Web = Ctx.Web;
Ctx.Load(Web);
Ctx.ExecuteQuery();
clientOM.List list = Web.Lists.GetByTitle(Libname);
Ctx.Load(list);
Ctx.ExecuteQuery();
clientOM.CamlQuery CamlQuery = new clientOM.CamlQuery();
CamlQuery.ViewXml = query;
clientOM.ListItemCollection Items = list.GetItems(CamlQuery);
Ctx.Load(Items);
Ctx.ExecuteQuery();
if(Items.Count > 0)
{
clientOM.ListItem Item = Items.GetById(Items[0].Id);;
Ctx.Load(Item);
Ctx.ExecuteQuery();
if(Item.DisplayName == Packagename)
{
Item[PackageStatus] = DeploymentSucceeded;
Item.Update();
Ctx.ExecuteQuery();
}
}
}
}
All used fields like DisplayName, Id and PackageStatus should be specified manually. You can use CAML query and write something like this:
string queryText = #"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='{0}'/>
<Value Type='Text'>{1}</Value>
</Eq>
</Where>
</Query>
</View>";
CamlQuery query = new CamlQuery();
query.ViewXml = string.Format(queryText, 'DisplayName', Packagename); //FieldRef = internal field name
ListItemCollection listItems = list.GetItems(query);
Ctx.Load(listItems, items => items.Include(item => item[PackageStatus]);
Ctx.ExecuteQuery();
if (listItems.Count > 0)
{
listItems[0][PackageStatus] = DeploymentSucceeded;
Item.Update();
Ctx.ExecuteQuery();
}
I see a fix.
Instead of using Item.DisplayName, I can use File object. It works when I use File and instantiating it by load(File) like other property.
clientOM.File file = Item.File;
Ctx.Load(file);
Ctx.ExecuteQuery();
if(file.Name == Packagename)
{
Item[PackageStatus] = DeploymentSucceeded;
Item.Update();
Ctx.ExecuteQuery();
}
I need to get GUID of an item. I know the SiteURL, List Name and Item Name. How do I get guid of this item insead to using splistitem li in list.items and loop through each item (if li.name==myitemname then assign strguid=li.uniqueid.tostring()
Is there a way not to use foreach loop since I know the name of the item? This will save time to loop throught items.
If you are creating a spquery on your unique item in splistcollection you would be returned only one element which you can obtain without foreach
using (SPSite site = new SPSite(SiteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList apps = web.GetList(web.Url + "/Lists/MyList");
SPQuery query = new SPQuery();
query.Query = String.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='String'>{0}</Value></Eq></Where>", _title);
items = apps.GetItems(query);
if(items.Count > 0)
{
Guid id = items[0].UniqueId;
}
}
}
Works but I have 11 files and they all have the same file name "license.txt" and they are in the same document library. 1 file "license.txt" is under the root document library and other 10 in 10 different folders within a document library. so what if i am looking for the license.txt file that's in Demo folder?
This code works but only finds license.txt under the root.
private void btnGetFileGuid_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
{
using (SPWeb web = site.OpenWeb())
{
SPList spList = web.Lists["Auto Cad"];
string fileName = "license.txt";
SPQuery query = new SPQuery();
query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
SPListItemCollection items = spList.GetItems(query);
if (items.Count > 0)
{
Guid id = items[0].UniqueId;
lblGuid.Text = id.ToString();
}
}
}
}
Trying the following and it seems to be working.
query.ViewAttributes = "Scope=\"Recursive\"";
or
query.ViewAttributes = "Scope='RecursiveAll'";
I'm trying to display the ListItems in a gridview.
Please help me in finding a way to access the list items.
using (SPSite site = new SPSite("http://mysitehere......"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["TestList"];
.......
.......
}
}
Please help me in accessing the list item values.
The below code should do the trick, get the full article from msdn here
using (SPSite site = new SPSite("http://mysitehere......"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["TestList"];
SPListItemCollection collListItems = list.Items;
foreach (SPListItem oListItem in collListItems)
{
string value = SPEncode.HtmlEncode(oListItem["Field1_Name"]);
// do something with value
}
}
}
You may use any of the below:
SPList list;
foreach (SPListItem item in list.Items)
{
string title = item["Title"];
}
SPQuery query = new SPQuery();
query.ViewFields = "<FieldRef Name='Title'/>";
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in list.Items)
{
string title = item["Title"];
}
for (int i = 0; i < list.Items.Count; i++ )
{
string title = list.Items[i]["Title"];
}
From the performance point of view, I suggest using the SP Query as then you can specify which fields to fetch and whether or not to fetch any associated metadata with the list items. This results in fewer db calls.
Kind regards,
Use SPDataSource to display list items in a grid view, i.e. create and configure an SPDataSource object and bind it to a SPGridView control.
For displaying items in a gridview (if you don't want to use SPGridView), I would use the GetDataTable method, instead of using a foreach loop as many of the answers do.
if (items.Count > 0)
{
DataTable dt = items.GetDataTable();
GridView1.DataSource = dt;
GridView1.DataBind();
}
Well, I haven't done any sharepoint work, but I believe you can use:
foreach (SPListItem item in list.Items)
or
foreach (SPListItem item in list.GetItems(view)) // or query
or access by index or guid:
SPListItem item = list.Items[10];
SPListItem item = list.Items[guid];
The SPQuery approach as suggested by unknown(yahoo) is the way to go, however you should remember that the default rowlimit of SPQuery is 100:
try
{
using (SPSite site = new SPSite(theURL))
{
SPWeb web = site.OpenWeb();
SPList list = web.Lists["TheNameOfTheList"];
//search each ListItem where the date is after 1/1 2009
SPQuery query = new SPQuery();
//the default is 100, which is less then the expected max
query.RowLimit = 500;
// The U2U CAML Query builder rules :-)
query.Query = "<Where><Gt><FieldRef Name='StartDate' /><Value Type='DateTime'>";
query.Query += "2009-01-01T00:00:00Z</Value></Gt></Where>";
SPListItemCollection resultset = list.GetItems(query);
foreach (SPListItem item in resultset)
{
// do something
}
}
}
If you´re using .NET 3.5 I would recommend using the linq datasource together with the spgridview to bind splistitems to a gridview. Saves you a lot of time.
I have an example of this on my blog.
To display images you have to get the url of the image. Here is an example of that:
SPListItem item = GetItem();
string imagefieldhtml = item["NameOfImageField"].ToString();
ImageFieldValue imagefield = new ImageFieldValue(imagefieldhtml);
var url = imagefield.ImageUrl;
The url variable will now hold the image url.
Ok, I have solved the above issue. In my case I did not need to use the SPEncode.HTML, so I have commented out everything that's not needed. Here is the fixed code if anyone else needs it:
using (SPSite site3 = SPContext.Current.Site)
{
using (SPWeb web2 = site3.OpenWeb())
{
// SPWeb site3 = SPContext.Current.Site.RootWeb;
SPList list2 = web2.Lists["Configuration"];
SPListItemCollection collListItems = list2.Items;
foreach (SPListItem oListItem in list2.Items)
{
//string value = SPEncode.HtmlEncode.ToString(oListItem["List name"]);
string valueListName = oListItem["List name"].ToString();
string valueListURL = oListItem["List URL"].ToString();
}
}
}