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

前端之家收集整理的这篇文章主要介绍了如何使用c#在Sharepoint库子文件夹中上传文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在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?
        }
    }
}

解决方法

使用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);   
}
原文链接:https://www.f2er.com/csharp/92436.html

猜你在找的C#相关文章