我需要在sharepoint库中使用c#console app上传文件.我设法只将它上传到父库.但要求是将其上传到其子文件夹.
所以这是文件夹结构:
我需要将它上传到子文件夹3.现在,我只能上传根文件夹.
当我尝试在GetByTitle方法中输入子文件夹3时会抛出错误,但是当它是根文件夹时,它会成功上载.
这是我的代码.
using (ClientContext clientContext = new ClientContext(siteURL)) { clientContext.Credentials = new System.Net.NetworkCredential(@"username","password","domain"); var web = clientContext.Web; // Create the new file var newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(@"C:\filepath\test.xlsx"); newFile.Overwrite = true; newFile.Url = "Test Upload.xlsx"; List list = web.Lists.GetByTitle("Service Oriented Architecture (SOA)"); clientContext.Load(list); clientContext.ExecuteQuery(); clientContext.Load(list.RootFolder); clientContext.Load(list.RootFolder.Folders); clientContext.ExecuteQuery(); foreach (Folder SubFolder in list.RootFolder.Folders) { if (SubFolder.Name.Equals("07 - SOA Environment")) { //What's next? } } }
解决方法
使用CSOM上传文件时,如何指定子文件夹有多种选择
关于下面提供的解决方案有两个假设:
>库名称(url)是Documents,具有以下文件夹结构:
文件夹/子文件夹/子子文件夹/子子文件夹/
>文件夹结构已存在
使用FileCreationInformation.Url属性
使用FileCreationInformation.Url property为上载的文件指定文件夹URL.
以下示例演示如何指定相对url(示例的略微修改版本,主要区别在于指定FileCreationInformation.Url)
var uploadFilePath = @"c:\tmp\SharePoint User Guide.docx"; var fileCreationInfo = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(uploadFilePath),Overwrite = true,Url = Path.Combine("Documents/Folder/Sub Folder/Sub Sub Folder/Sub Sub Sub Folder/",Path.GetFileName(uploadFilePath)) }; var list = context.Web.Lists.GetByTitle("Root Folder"); var uploadFile = list.RootFolder.Files.Add(fileCreationInfo); context.Load(uploadFile); context.ExecuteQuery();
使用Web.GetFolderByServerRelativeUrl方法
使用Web.GetFolderByServerRelativeUrl method检索必须上载文件的文件夹:
public static void UploadFile(ClientContext context,string uploadFolderUrl,string uploadFilePath) { var fileCreationInfo = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(uploadFilePath),Url = Path.GetFileName(uploadFilePath) }; var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl); var uploadFile = targetFolder.Files.Add(fileCreationInfo); context.Load(uploadFile); context.ExecuteQuery(); }
using (var ctx = new ClientContext(webUri)) { ctx.Credentials = credentials; UploadFile(ctx,"Documents/Folder/Sub Folder/Sub Sub Folder/Sub Sub Sub Folder",filePath); }