如何使用c#在Sharepoint库子文件夹中上传文件?

kem*_*yyy 7 .net c# sharepoint file-upload sharepoint-2010

我需要在sharepoint库中使用c#console app上传文件.我设法只将它上传到父库.但要求是将其上传到其子文件夹.
所以这是文件夹结构:

根文件

- 子文件夹1 ---子文件夹2
----子文件夹3

我需要将它上传到子文件夹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?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Vad*_*hev 12

使用CSOM上传文件时,如何指定子文件夹有多种选择

关于下面提供的解决方案有两个假设:

  1. 库名称(url)是Documents并具有以下文件夹结构: Folder/Sub Folder/Sub Sub Folder/Sub Sub Sub Folder/

  2. 文件夹结构已存在

使用FileCreationInformation.Url财产

使用FileCreationInformation.Url属性指定上载文件的文件夹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();
Run Code Online (Sandbox Code Playgroud)

使用Web.GetFolderByServerRelativeUrl方法

使用Web.GetFolderByServerRelativeUrl方法检索必须上载文件的文件夹:

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();
}
Run Code Online (Sandbox Code Playgroud)

用法

using (var ctx = new ClientContext(webUri))
{
     ctx.Credentials = credentials;

     UploadFile(ctx,"Documents/Folder/Sub Folder/Sub Sub Folder/Sub Sub Sub Folder",filePath);   
}
Run Code Online (Sandbox Code Playgroud)

  • 有效!非常感谢!像魅力一样工作! (2认同)
  • "根文件夹"是指"文档"还是"文件夹"? (2认同)