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?
Related
I have to copy a file on a sharepoint site.
I have seen that the only authentication working is with the AuthenticationManager.
So this works:
var authManager = new AuthenticationManager();
var ctx = authManager.GetWebLoginClientContext(strHexagon);
Web web = ctx.Web;
User user = web.CurrentUser;
ctx.Load(web);
ctx.Load(user);
ctx.ExecuteQuery();
lbxInfo.Items.Add(web.Title);
lbxInfo.Items.Add(user.LoginName);
Now, after having authenticated I need to copy a file to the sharepoint site.
I have seen that there is ctx.Web.SaveFileToLocal but what if I have to copy from local to sharepoint?
Thanks
You can use the OfficeDevPnP.Core library
string str1_Url=... <--- sharepoint site
string str2_FileSource_Full= #"C:\temp\A.txt";
string str3_FileDestination_NameExt="B.txt";
string str4_TopDestination_Folder=... <--- sharepoint site title folder
string str5_TopDestination_SubFolder=... <--- folder e.g. Production
string str6_TopDestination_AllSubFolders=...<--- subfolder e.g. Test
// AuthenticationManager -> ByPasses Multi-Factor Authentication
var authManager = new AuthenticationManager();
var ctx = authManager.GetWebLoginClientContext(str1_Url);
// Web & User definitions
Web web = ctx.Web;
User user = web.CurrentUser;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(str2_FileSource_Full);
// Rename the destination file
newFile.Url = str3_FileDestination_NameExt;
Microsoft.SharePoint.Client.List docs = web.Lists.GetByTitle(str4_TopDestination_Folder);
// Selects a Folder inside the root one
Microsoft.SharePoint.Client.Folder folder = docs.RootFolder.Folders.GetByUrl(str5_TopDestination_SubFolder);
folder.Folders.Add(str6_TopDestination_AllSubFolders);
var targetFolder = folder.Folders.GetByUrl(str6_TopDestination_AllSubFolders);
// Uploads a file to the targetFolder
newFile.Overwrite = true;
Microsoft.SharePoint.Client.File uploadFile = targetFolder.Files.Add(newFile);
// Executes query
ctx.Load(docs);
ctx.Load(uploadFile);
ctx.Load(web);
ctx.Load(user);
ctx.ExecuteQuery();
I need to save files from the existing AngularJS/.NET application to Sharepoint. Most of the examples I see online is when applications reside on Sharepoint itself. How do I save files from outside?
I've been given a user access to our organization's Sharepoint site but no application user passwords. What do I need to request from administrators of SharePoint site to be able to write the code?
We can use CSOM C# code to upload file to SharePoint 2010 document library. We need use an admin user and password to pass the Credentials in the .NET application server.
public static void UploadFile(ClientContext context, string uploadFolderUrl, string uploadFilePath)
{
var fileCreationInfo = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(uploadFilePath),
Overwrite = true,
Url = Path.GetFileName(uploadFilePath)
};
var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
var uploadFile = targetFolder.Files.Add(fileCreationInfo);
context.Load(uploadFile);
context.ExecuteQuery();
}
Usage
var siteUrl="http://sp2010";
var username="admin";
var password="xx";
var domainName="domain1";
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = new System.Net.NetworkCredential(username, password, domainName);
UploadFile(ctx,"Documents/folder1",#"c:\upload\test.docx");
}
The following article for your reference.
Uploading files using Client Object Model in SharePoint 2010
I'm new to sharepoint. Im trying to upload a file and add metadata to the file. Below is my code. I can see some internal exceptions are their while declaring ClientContext
Exception: clientContext.ServerVersion threw an exception of type PropertyOrFieldNotInitializedException
The same is happening for Site, Web.
using (ClientContext clientContext = new ClientContext(SPURL))
{
//ClientContext clientContext = new ClientContext(SPURL);
clientContext.Credentials = new System.Net.NetworkCredential(userName, password, domain);
Web web = clientContext.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(PPTPath);
newFile.Url = "F:\\log.txt";
List docs = web.Lists.GetByTitle("Test");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
clientContext.ExecuteQuery();
using (FileStream fileStream =
new FileStream(PPTPath, FileMode.Open))
ClientOM.File.SaveBinaryDirect(clientContext,
DocumentRepository + PPTfilename, fileStream, true);
}
the CSOM libraries expect you to tell them what you want to query from the SharePoint environment upon calling ExecuteQuery().
Therefor you need to tell the clientcontext object what you want to load.
For instance:
Web web = clientContext.Web; should be followed by clientContext.Load(web);
This is a simple example. For uploading files your best bet is making use of the File.SaveBinaryDirect function. An example on how to use it can be found elsewhere on stackoverflow.
i am trying to upload a file to sharepoint with c# using the microsoft sharepoint client
i have no issues when i create my context and give it my username and password like this
using (ClientContext ctx = new ClientContext(spSite))
{
if (!System.IO.File.Exists(fileLocation))
throw new FileNotFoundException("File not found.", fileLocation);
var credentials = new NetworkCredential("username", "password");
ctx.Credentials = credentials;
Web web = ctx.Web;
ctx.Load(user);
ctx.ExecuteQuery();
String fileName = System.IO.Path.GetFileName(fileLocation);
FileStream fileStream = System.IO.File.OpenRead(fileLocation);
ctx.Load(web.Folders);
ctx.ExecuteQuery();
Folder spFolder = web.Folders.FirstOrDefault(x => x.Name.Equals(spListCleanName));
FileCreationInformation fci = new FileCreationInformation();
fci.Url = spSite + spLibraryName + file;
byte[] bytes = System.IO.File.ReadAllBytes(fileLocation);
fci.Content = bytes;
Microsoft.SharePoint.Client.File spFile = spFolder.Files.Add(fci);
spFile.ListItemAllFields.Update();
ctx.ExecuteQuery();
}
but my issue comes in the network credentials part. is there a way to use the current users credentials (through iis or .net or anything) so that i don't have to ask for their password? since that isn't something we want to save in plain text anywhere.
thank you in advance
Use the CredentialCache.DefaultCredentials (https://msdn.microsoft.com/en-us/library/system.net.credentialcache.defaultcredentials(v=vs.110).aspx) instead of NetworkCredential object.
This will use the users security context.
Is there a way to automatically upload a file in Sharepoint 2010 using c#? We have no administrative control on the Sharepoint server. We just need to write a program that will upload a local file to a designated sharepoint library. The program will run on our server which in no way affiliated with the sharepoint server.
The following options could be considered for uploading the file into SharePoint via CSOM.
Prerequisites: SharePoint Foundation 2010 Client Object Model Redistributable
Using FileCollection.Add method
FileCollection.Add method adds a file to the collection based on provided file creation information
public static void UploadFile(ClientContext context, string uploadFolderUrl, string uploadFilePath)
{
var fileCreationInfo = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(uploadFilePath),
Overwrite = true,
Url = Path.GetFileName(uploadFilePath)
};
var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
var uploadFile = targetFolder.Files.Add(fileCreationInfo);
context.Load(uploadFile);
context.ExecuteQuery();
}
Usage
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = credentials;
UploadFile(ctx,"Documents/Orders",#"c:\upload\user guide.docx");
}
where Orders is a folder in Documents library
According to Uploading files using Client Object Model in SharePoint 2010:
The above code might fail throwing a (400) Bad Request error depending
on the file size.
Using File.SaveBinaryDirect method
File.SaveBinaryDirect method - uploads the specified file to a SharePoint site without requiring an ExecuteQuery() method call.
public static void UploadFile(ClientContext context, string folderUrl, string uploadFilePath)
{
using (var fs = new FileStream(uploadFilePath, FileMode.Open))
{
var fileName = Path.GetFileName(uploadFilePath);
var fileUrl = String.Format("{0}/{1}", folderUrl, fileName);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
}
}
Usage
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = credentials;
UploadFile(ctx,"/News/Documents/Orders",#"c:\upload\user guide.docx");
}
where Orders is a folder in Documents library located on web site News.
FolderUrl format: /<web url>/<list url>/<folder url>