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();
Related
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 have below code which is attempting to create a blank file on my azure file storage account
CloudStorageAccount sa = CloudStorageAccount.Parse(connectionString);
var fc = sa.CreateCloudFileClient();
var share = fc.GetShareReference("uploadparking");
share.CreateIfNotExists();
var rootDirectory = share.GetRootDirectoryReference();
var subDirectory = rootDirectory.GetDirectoryReference("valuationrequests");
subDirectory.CreateIfNotExists();
var uri = new Uri(subDirectory.Uri.ToString() + "/file.txt");
var file = new CloudFile(uri);
file.Create(0);
On the final line I am getting the following exception:
Microsoft.WindowsAzure.Storage.StorageException' occurred in Microsoft.WindowsAzure.Storage.dll
Additional information: The remote server returned an error: (404) Not Found.
I'm not sure what it can't find. It shouldn't be trying to find the file as it's creating it. I have confirmed the directories exist.
If anyone knows I can go about creating a file successfully please let me know. I've checked the tutorials and they sadly only show how to download a file not upload.
I believe the documentation is incorrect. The documentation only mentions that the URI should be absolute. It fails to mention that if you're using absolute URI, then you should also pass storage credentials or the URI should include Shared Access Signature with at least Create permission to create a file.
You should try using the following override of CloudFile to create an instance: https://learn.microsoft.com/en-us/dotnet/api/microsoft.windowsazure.storage.file.cloudfile.-ctor?view=azurestorage-8.1.3#Microsoft_WindowsAzure_Storage_File_CloudFile__ctor_System_Uri_Microsoft_WindowsAzure_Storage_Auth_StorageCredentials_.
So your code would be:
CloudStorageAccount sa = CloudStorageAccount.Parse(connectionString);
var fc = sa.CreateCloudFileClient();
var share = fc.GetShareReference("uploadparking");
share.CreateIfNotExists();
var rootDirectory = share.GetRootDirectoryReference();
var subDirectory = rootDirectory.GetDirectoryReference("valuationrequests");
subDirectory.CreateIfNotExists();
var uri = new Uri(subDirectory.Uri.ToString() + "/file.txt");
var file = new CloudFile(uri, sa.Credentials);
file.Create(0);
Other alternative would be to create a Shared Access Signature (SAS) token on the share and use a SAS URL when creating an instance of CloudFile. So in this case your code would be:
CloudStorageAccount sa = CloudStorageAccount.Parse(connectionString);
var fc = account.CreateCloudFileClient();
var share = fc.GetShareReference("uploadparking");
share.CreateIfNotExists();
var rootDirectory = share.GetRootDirectoryReference();
var subDirectory = rootDirectory.GetDirectoryReference("valuationrequests");
subDirectory.CreateIfNotExists();
SharedAccessFilePolicy policy = new SharedAccessFilePolicy()
{
Permissions = SharedAccessFilePermissions.Create,
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15)
};
var sasToken = share.GetSharedAccessSignature(policy);
var uri = new Uri(subDirectory.Uri.ToString() + "/file1.txt" + sasToken);
var file = new CloudFile(uri);
file.Create(0);
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
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.