I'm newbie to Sharepoint and currently using Sharepoint Online. I'm in need of retrieving files under a sharepoint document library in C#.
We have couple of document library urls as follows:
https://customer1.sharepoint.com/DocumentFolder/Forms/AllItems.aspx
https://customer2.sharepoint.com/sites/sitename/DocumentFolder/SubFolder/Forms/AllItems.aspx
I need to extract DocumentFolder name in case of URL 1 above, and DocumentFolder/SubFolder name in case of URL 2
Using Sharepoint REST service, I then would like to list files under DocumentFolder :
http://site url/_api/web/GetFolderByServerRelativeUrl('/DocumentFolder')
The challenge I have is to extract the DocumentFolder for the above URLs, as I could not find any API/method call to extract the DocumentFolder. I could try regex on the url, but it'll be helpful, if there is a right way to extract the DocumentFolder/SubFolder, that will be helpful.
We can use CSOM C# with CAML query to achieve it, set the view as < View Scope='RecursiveAll'>, thus gets the documents from root folder and its sub folders.
string targetSiteURL = #"https://xxx.sharepoint.com/sites/sitename";
var login = "xxx#xxx.onmicrosoft.com";
var password = "xxx";
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(login, securePassword);
ClientContext ctx = new ClientContext(targetSiteURL);
ctx.Credentials = onlineCredentials;
List list = ctx.Web.Lists.GetByTitle("Documents");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='RecursiveAll'><Query></Query></View>";
camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
foreach (var item in listItems)
{
if (item.FileSystemObjectType == FileSystemObjectType.File)
{
// This is a File
}
else if (item.FileSystemObjectType == FileSystemObjectType.Folder)
{
// This is a Folder
}
}
More information for your reference:
http://www.sharepointpals.com/post/How-to-Get-All-the-Files-within-a-Folder-using-CAML-Query-in-SharePoint-Office-365-using-C-CSOM
Related
Situation:
I´m currently adding items to a sharepointlist via a .Net page and i can´t get them to display properly.
I get all the items (printer modells) from the list but displaying them in a dropdown list (modell) is not going well and the list only displays "Microsoft.Sharepoint.Client.ListItem".
Without datavaluefield and datatextvalue commented out I get errors about the fields not being found. This despite having recreated the column (to ensure that the internal name is correct) and trying both "value" and "key" in both fields with the same result.
Frankly, I´m out of ideas and googling the problem haven´t helped, even more so since most solutions refer to SPlists which is not an option.
using (ClientContext context = new ClientContext("[mysite]"))
{
context.Credentials = new SharePointOnlineCredentials(username, password);
Web site = context.Web;
List list = site.Lists.GetByTitle("Printers");
CamlQuery query = CamlQuery.CreateAllItemsQuery();
ListItemCollection collection = list.GetItems(query);
context.Load(collection);
context.ExecuteQuery();
modell.DataSource = collection;
//modell.DataValueField = "Printermodell";
//modell.DataTextField = "Printermodell";
modell.DataBind();
}
Thankfull for any idéas / recommendations!
Sample code for your reference.
using (ClientContext context = new ClientContext("https://domain.sharepoint.com/sites/Developer/"))
{
string userName = "user.onmicrosoft.com";
string password = "pw";
SecureString securePassword = new SecureString();
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials(userName, securePassword);
Web site = context.Web;
List list = site.Lists.GetByTitle("MyList2");
CamlQuery query = CamlQuery.CreateAllItemsQuery();
Microsoft.SharePoint.Client.ListItemCollection collection = list.GetItems(query);
context.Load(collection);
context.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem item in collection)
{
string text = string.Format("{0}",item.FieldValues["Title"]);
modell.Items.Add(new System.Web.UI.WebControls.ListItem(text, item.Id.ToString()));
}
//modell.DataSource = collection;
//modell.DataValueField = "Printermodell";
//modell.DataTextField = "Printermodell";
//modell.DataBind();
}
My question is about sharepoint online.
In my project I want to download the list item with its versions. I am able to download the current list item version but not able to download its version. I have referred this answer which shows how to calculate the Canonical and Revision paths. But while fetching the data I am getting error as
The remote server returned an error: (403) Forbidden.
and in response header getting value as "Access denied. Before opening files in this location%2c you must first browse to the web site and select the option to login automatically."
string url = "https://test.sharepoint.com/teams/Mycompany";
ScureString f_SecurePass = new SecureString();
foreach (char ch in password)
f_SecurePass.AppendChar(ch);
clientcontext = new ClientContext(url);
var credentials = new SharePointOnlineCredentials(userid, f_SecurePass);
clientcontext.Credentials = credentials;
Web web = clientcontext.Web;
clientcontext.Load(web, website => website.Lists);
clientcontext.ExecuteQuery();
CamlQuery camlQ = new CamlQuery();
camlQ.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" +
"<Value Type='Number'>0</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>";
var cq = _list.GetItems(camlQ);
clientcontext.Load(cq, items => items.Include(item => item.Id,
item=>item.EffectiveBasePermissionsForUI,
item=>item.EffectiveBasePermissions));
clientcontext.ExecuteQuery();
var itm = _list.GetItemById(itemid);
clientcontext.Load(itm, r => r.Id, r => r.DisplayName);
clientcontext.ExecuteQuery();
foreach (FileVersion itemVersion in itm.File.Versions)
{
int size = itemVersion.Size;
string versionlbl = itemVersion.VersionLabel;
string newversion = url + itemVersion.Url;
System.WebClient client = new System.Net.WebClient();
client.Credentials = new NetworkCredential(userid, f_SecurePass);
System.IO.Stream Data = client.OpenRead(newversion);// Throws exception
}
How can I download the list item versions?
UPDATE: If I try to download file version by using
File.OpenBinaryDirect(clientcontext, newversion);
it throws following error
Message = "Specified argument was out of the range of valid values.\r\nParameter name: serverRelativeUrl"
I am able to download file version using update CSOM apis.
Please refer
https://social.msdn.microsoft.com/Forums/en-US/802ecc6f-4a4d-4933-bf54-e68e5882203b/how-can-i-download-the-list-item-versions?forum=appsforsharepoint
I am trying to get the image url from a list but dont now how. the usual search on google didnt help. This is my code so far:
using(var context = MySession.Current.spcontext.CreateAppOnlyClientContextForSPHost())
{
List<Produkt> produkter = new List<Produkt>();
ListItemCollection listFromSharePoint = _foodRepo.RetriveList(context, PRODUKTER);
foreach(ListItem items in listFromSharePoint)
{
Produkt oneItem = new Produkt();
oneItem.bild = (string)items["Bild"]; <--Column name is "Bild" but how to get the url?
produkter.Add(oneItem);
}
ViewBag.Produkter = produkter;
}
image of what I want:
everything loads from sharepoint, but dont know how to reach the url. any ideas?
When accessing the itemvalues, they are always an object which has to be casted to the correct class:
using (ClientContext ctx = new ClientContext(url))
{
Web web = ctx.Web;
List list = web.Lists.GetById(listId);
ListItem item = list.GetItemById(itemId);
ctx.Load(item);
ctx.ExecuteQuery();
FieldUrlValue fieldValue = (FieldUrlValue)item["Bild"]; //<-- casting!
string bildUrl = fieldValue.Url; //<-- here you can access the values
}
How I can upload image to a SharePoint List "custom List" not library using CSOM C#?
Here is what I have tried so far:
FieldUrlValue url = new FieldUrlValue();
url.Url = FileUpload.PostedFile.FileName;
url.Description = "Your description here";
newItem["Image"] = url;
You can use this code to upload documents into SharePoint via the CSOM:
using (ClientContext ctx = new ClientContext("http://urlToYourSiteCollection")) {
FileCreationInformation fci = new FileCreationInformation();
fci.Content = System.IO.File.ReadAllBytes("PathToSourceDocument");
fci.Url = System.IO.Path.GetFileName("PathToSourceDocument");
Web web = ctx.Web;
List targetDocLib = ctx.Web.Lists.GetByTitle("yourTargetLibrary");
ctx.ExecuteQuery();
Microsoft.SharePoint.Client.File newFile = targetDocLib.RootFolder.Files.Add(fci);
ctx.Load(newFile);
ctx.ExecuteQuery();
}
If you want to set properties of the new item, you can do it this way:
ListItem lItem = newFile.ListItemAllFields;
lItem.File.CheckOut(); //CHECK OUT VERY IMPORTANT TO CHANGE PROPS
ctx.ExecuteQuery();
lItem["yourProperty"] = "somewhat";
lItem.Update();
lItem.File.CheckIn("Z", CheckinType.OverwriteCheckIn);
ctx.ExecuteQuery();
If you need to upload files to a SharePoint site please visit the following link where it is explained how to read and upload files using CSOM
How to download/upload files from/to SharePoint 2013 using CSOM?
I'm trying to add permissions to specific folders within a document library using the SharePoint 2013 Client Object Model in C#. In effect I'm trying to reproduce the behaviour you get when you "Share" a folder via the UI. This is the code I've got so far, but its not giving the behaviour I'm after. In the code I'm trying to add a single user to the RoleAssigments collection of the folder. Note: The document library does not inherit permissions from the site level.
using (ClientContext ctx = new ClientContext(SPSiteURL))
{
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
Web web = ctx.Web;
Folder AccountFolder = web.GetFolderByServerRelativeUrl("account/" + OurFolderName);
ctx.Load(AccountFolder);
ctx.ExecuteQuery();
ListItem AllFields = AccountFolder.ListItemAllFields;
ctx.Load(AllFields);
ctx.ExecuteQuery();
// Add the user to SharePoint, if they have not already been added
Principal AccountUser = ctx.Web.EnsureUser(UsersName);
ctx.Load(AccountUser);
ctx.ExecuteQuery();
var info = Utility.ResolvePrincipal(ctx, ctx.Web, AccountUser.LoginName, PrincipalType.All, PrincipalSource.All, null, false);
context.ExecuteQuery();
Principal ResolvedUser = context.Web.EnsureUser(info.Value.LoginName);
ctx.Load(ResolvedUser);
ctx.ExecuteQuery();
// Get the existing RoleAssignments collection for the folder
RoleAssignmentCollection RoleAssignments = AllFields.RoleAssignments;
// Create a new RoleDefinitionBindingCollection object
RoleDefinitionBindingCollection collRDB = new RoleDefinitionBindingCollection(ctx);
// Get the default "Contribute" role and add it to our RoleDefinitionBindingCollection
RoleDefinition ContributeRoleDef = ctx.Web.RoleDefinitions.GetByName("Contribute");
collRDB.Add(ContributeRoleDef);
// Break the Role Inheritance, but copy the parent roles and propagate our roles down
AllFields.BreakRoleInheritance(true, true);
// Add our new RoleAssigment to the RoleAssignmentCollection for the folder
RoleAssignments.Add(ResolvedUser, collRDB);
// Push our permission update back to SharePoint
ctx.ExecuteQuery();
}
The following example demonstrates how to share folder using CSOM API:
using (var ctx = new ClientContext(webUri))
{
var folder = ctx.Web.GetFolderByServerRelativeUrl("/Shared Documents/Archive");
var folderItem = folder.ListItemAllFields;
//grant Read permissions to 'Everyone' Sec Group
var everyoneSecGroup = ctx.Web.SiteUsers.GetById(4); //get Everyone security group
ShareListItem(folderItem, everyoneSecGroup, "Read");
}
where
public static void ShareListItem(ListItem listItem, Principal principal, string permissionLevelName)
{
var ctx = listItem.Context as ClientContext;
var roleDefinition = ctx.Site.RootWeb.RoleDefinitions.GetByName(permissionLevelName);
listItem.BreakRoleInheritance(true, false);
var roleBindings = new RoleDefinitionBindingCollection(ctx) { roleDefinition };
listItem.RoleAssignments.Add(principal, roleBindings);
ctx.ExecuteQuery();
}
Result