I'm trying to change the field values for files stored in a Sharepoint List programmatically, but it seems i can't access these. There have been some helpful ideas and they look very promising, but it seems not to work at all. Here my code so far:
ClientContext context = new ClientContext(#"https://.........de");
Microsoft.SharePoint.Client.File file = context.Web.GetFileByServerRelativeUrl(#"https://............de/software/ap_ck/Dokumenten%20Management%20System/100_001_000_1.txt");
ListItem lstitem = file.ListItemAllFields;
context.Load(lstitem);
context.ExecuteQuery();
lstitem["Mandant"] = "Mercedes";
lstitem.Update();
context.ExecuteQuery();
Is there maybe something wrong with the code itself?
In Line two GetFileByServerRelativeUrl method, it needs the file relative url, please check the working demo below:
ClientContext context = new ClientContext(#"http://sp2016/sites/test");
Microsoft.SharePoint.Client.File file = context.Web.GetFileByServerRelativeUrl(#"/sites/test/Documents1/folder2/test.txt");
ListItem lstitem = file.ListItemAllFields;
context.Load(lstitem);
context.ExecuteQuery();
lstitem["Title"] = "Mercedes";
lstitem.Update();
context.ExecuteQuery();
Related
I got stuck in a situation. I uploaded a file in Sharepoint programmatically in C# using the CSOM library,
FileCreationInformation newfile = new FileCreationInformation();
byte[] FileContent = dstStream.ToArray();
newfile.ContentStream = new MemoryStream(FileContent);
newfile.Url = strfilename;
Microsoft.SharePoint.Client.File uploadfile = destiFolder.Files.Add(newfile);
context.Load(uploadfile);
context.ExecuteQuery();
I used above mentioned approach to upload a file in a particular folder.
Now the thing is I need to update that file's 'Created By'/'Modified By' field with another Username.
So can anybody help me out of this ?
You can update list item field values
// checkout
uploadfile.CheckOut();
// get list item field values
ListItem item = uploadfile.ListItemAllFields;
// ensure User object, specify the correct login name
User anotherUser = context.Web.EnsureUser("Contoso\\JohnDoe");
context.Load(anotherUser);
context.ExecuteQuery();
// update Author and Editor field
item["Editor"] = anotherUser;
item["Author"] = anotherUser;
// update item
item.Update();
// checkin
uploadfile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
context.ExecuteQuery();
I know this question has been asked in the past, but I can't seem to find a working solution.
I want to update The CreatedDateTime, ModifiedBy and CreatedBy metadata on a file that I uploaded with CSOM. I have this code. It does not crash, but does not update the properties either.
FileCreationInformation newFile = new FileCreationInformation();
byte[] FileContent = null;
using (var webClient = new WebClient())
{
webClient.Headers.Add("Authorization", authorization);
FileContent = webClient.DownloadData(file.DowlnloadUrl);
}
newFile.ContentStream = new System.IO.MemoryStream(FileContent);
newFile.Url = System.IO.Path.GetFileName(file.Name);
Microsoft.SharePoint.Client.File sharepointFile = _spFolder.Files.Add(newFile);
_context.ExecuteQuery();
sharepointFile.ListItemAllFields["Modified"] = DateTime.Today.AddDays(-3);
sharepointFile.ListItemAllFields["Created"] = DateTime.Today.AddDays(-3);
sharepointFile.ListItemAllFields.Update();
_context.ExecuteQuery();
The file still appears that it was created/modified a few seconds ago.
Any help would be appreciated. PS: if this can be done in one go (one single ExecuteQuery), that would be great.
I ended up finding a code snippet that works.
Beware, this works only if the account your are using to generate the context is a Sharepoint Admin (has the SP admin role, and not only a Global Admin role).
Being an owner of the site does not suffice either.
Code can be found here:
https://www.c-sharpcorner.com/blogs/update-a-sharepoint-listitem-without-increasing-its-item-file-version-using-sharepoint-client-side-modelcsom
Although this works, it seems rather verbose. Is there a more terse way? Using CSOM and a C# .Net Framework application. Really just want to delete the folder and contents. Thanks.
public static void DeleteFileAndFolder(string file)
{
using (var context = Sharepoint.ClientContext)
{
context.Credentials = new NetworkCredential(
Sharepoint.ExtranetUserName,
Sharepoint.ExtrantPassword);
var web = context.Web;
var list = web.Lists.GetByTitle(Sharepoint.ListTitle);
var deleteFile = list.RootFolder.FindFiles(file).Single();
deleteFile.Context.Load(deleteFile.ListItemAllFields);
deleteFile.Context.ExecuteQuery();
var folderUrl = deleteFile.ListItemAllFields["FileDirRef"].ToString();
var folder = deleteFile.ListItemAllFields.ParentList.ParentWeb.GetFolderByServerRelativeUrl(folderUrl);
deleteFile.Context.Load(folder);
deleteFile.Context.ExecuteQuery();
deleteFile.DeleteObject();
folder.DeleteObject();
context.ExecuteQuery();
}
}
You don`t need to get list, you can get folder from web object, see sample to delete files in folder:
ClientContext ctx = GetCtx();
Folder rootFolder = ctx.Web.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl("your path here"));
ctx.Load(rootFolder, f => f.Files);
ctx.ExecuteQuery();
foreach (var file in rootFolder.Files)
{
file.DeleteObject();
}
ctx.ExecuteQuery();
Through C#, I'm trying to download a file from SharePoint (SharePoint 2016). Below is the code I'm using:
site = new ClientContext(url);
//credential setting has no issues. So I am skipping it. I am using NetworkCredentials
site.Load(web);
site.ExecuteQuery();
List list = web.Lists.GetByTitle("Documents");
site.Load(list);
site.ExecuteQuery();
site.Load(list.RootFolder);
site.ExecuteQuery();
site.Load(list.RootFolder.Folders);
site.ExecuteQuery();
Folder folder = web.GetFolderByServerRelativeUrl(sharePointPath);
site.Load(folder);
site.ExecuteQuery();
site.Load(folder.Files);
site.ExecuteQuery();
While the last "site.ExecuteQuery()" is being executed, an exception is thrown:
ExceptionMessage: File not found
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream
But, there are files in that path and manually we are able to upload and download with the same credentials. URLs, Paths, etc have been double-checked and no issues with that.
When I print "folder.ItemCount", it is printing the correct no. of files in the folder. Only in ExecuteQuery for loading files, it is throwing exception.
Build settings: .NET framework 4.5 and x64
In other posts, people advised to change to .NET 3.5 but it was for SharePoint 2010. Further, changing it to 3.5 ends up in lot of build errors for me.
Please help in fixing this.
Here is the code snippet to download a file from SharePoint default Document library and save into a local folder:
static void Main(string[] args)
{
string siteUrl = "http://sp2016/sites/dev";
ClientContext clientContext = new ClientContext(siteUrl);
var list = clientContext.Web.Lists.GetByTitle("Documents");
var listItem = list.GetItemById(5);
clientContext.Load(list);
clientContext.Load(listItem, i => i.File);
clientContext.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
var fileName = Path.Combine(#"C:\Test", (string)listItem.File.Name);
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
}
I was working with collection and above solution did not work for me, here is how I did so that it can help someone.
List list = web.Lists.GetByTitle("Events");
ListItemCollection listItems = list.GetItems(cmlqry);
context.Load(listItems);
context.ExecuteQuery();
if (listItems != null)
{
foreach (var listItem in listItems)
{
Console.WriteLine("Id: {0}, Title: {1}", listItem["ID"].ToString(), listItem["Title"].ToString());
context.Load(listItem.AttachmentFiles);
context.ExecuteQuery();
foreach (var file in listItem.AttachmentFiles)
{
Console.WriteLine("File: {0}", file.FileName);
var fileRef = file.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileRef);
var fileName = Path.Combine(#"C:\temp\Events\", String.Format("{0}_{1}", listItem.Id, file.FileName));
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
}
}
}
I'm new in this theme but I search a lot I mean really lot before I asked it here. So my problem is that, when I create ListItem in my app and set the Fields that are required, everything looks all right. I can see the ListItem in my List with proper fields if I go to Sharepoint Online. But when I click on the ListItem the Fields are empty and on the top of the page is an error which says "Object reference not set to an instance of an object." I don't know if the issue is happening cos of my code or there is an issue with Sharepoint settings? I followed most of the guides here to go as far as I'm now. My code below.
SP.List targetList = ctx.Web.Lists.GetByTitle("Documents");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newListItem = targetList.AddItem(itemCreateInfo);
newListItem["Title"] = "Test_title";
newListItem["EAN_x0020_k_x00f3_d"] = "AnotherCodeWhichIsRequired";
newListItem.Update();
string strFilePath = #"PathToMyPDF";
byte[] bytes = System.IO.File.ReadAllBytes(strFilePath);
using (System.IO.MemoryStream mStream = new System.IO.MemoryStream(bytes))
{
SP.AttachmentCreationInformation aci = new SP.AttachmentCreationInformation();
aci.ContentStream = mStream;
aci.FileName = System.IO.Path.GetFileNameWithoutExtension(strFilePath);
newListItem.AttachmentFiles.Add(aci);
newListItem.Update();
ctx.ExecuteQuery();
}
It looks like you are using a document library.The code that you have used is for a sharepoint list.
To upload a file to document library and update its properties, modify your code as below:
string strFilePath = #"PathToMyPDF";
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(strFilePath);
newFile.Overwrite = true;
SP.List targetList = ctx.Web.Lists.GetByTitle("Documents");
Microsoft.SharePoint.Client.File uploadFile = targetList.RootFolder.Files.Add(newFile);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
uploadFile.ListItemAllFields["Title"] = "Test_title";
uploadFile.ListItemAllFields["EAN_x0020_k_x00f3_d"] = "AnotherCodeWhichIsRequired";
uploadFile.ListItemAllFields.Update();
ctx.ExecuteQuery();