如何在子文件夹SharePoint Online C#中创建子文件夹

时间:2018-06-01 13:38:52

标签: c# sharepoint sharepoint-online

我想在C#中的文档库中创建一些文件夹。

文件夹中的文件夹结构应如下所示:

" 98_Projekte" - > " Muster Mandant" - > " 01测试子文件夹"

在我的C#代码中,我只创建子文件夹" Muster Mandant"在" 98_Projekte"。这是正确的,但我希望之后在" Muster Mandant"中创建新的子文件夹。 (见第二个foreach)。

        public static void AddFolder(ClientContext context, string[] folders)
    {
        Web web = context.Web;
        var docLibrary = web.DefaultDocumentLibrary().RootFolder;
        context.Load(docLibrary);
        context.ExecuteQuery();

        foreach (Microsoft.SharePoint.Client.Folder subFolder in docLibrary.Folders)
        {
            if (subFolder.Name == "98_Projekte")
            {
                subFolder.Folders.Add("Muster Mandant");
                context.ExecuteQuery();
                docLibrary = subFolder;
                docLibrary.Update();
            }
        }
        foreach (Microsoft.SharePoint.Client.Folder subSubFolder in docLibrary.Folders)
        {
            if (subSubFolder.Name == "Muster Mandant")
            {
                foreach (string folder in folders)
                {
                    subSubFolder.Folders.Add(folder);
                }
            }
        }
        context.ExecuteQuery();
    }
}

你有解决方案吗?

2 个答案:

答案 0 :(得分:1)

您可以查看以下代码。

 public static Folder AddSubFolder(ClientContext context, Folder ParentFolder, string folderName)
        {
            Folder resultFolder=ParentFolder.Folders.Add(folderName);
            context.ExecuteQuery();
            return resultFolder;   
        }

        static void Main(string[] args)
        {
            using (var context = new ClientContext("https://domain.sharepoint.com/sites/TST/"))
            {
                string password = "pw";
                SecureString sec_pass = new SecureString();
                Array.ForEach(password.ToArray(), sec_pass.AppendChar);
                sec_pass.MakeReadOnly();
                context.Credentials = new SharePointOnlineCredentials("lee@domain.onmicrosoft.com", sec_pass);               

                Web web = context.Web;
                var folders = web.DefaultDocumentLibrary().RootFolder.Folders;
                context.Load(folders);
                context.ExecuteQuery();

                foreach (Folder subFolder in folders)
                {
                    if (subFolder.Name == "98_Projekte")
                    {
                       Folder parent1= AddSubFolder(context,subFolder,"Muster Mandant");
                       AddSubFolder(context, parent1, "01 Test Subfolder");   
                    }
                }

                Console.WriteLine("Done");
                Console.ReadKey();
            }

        }

答案 1 :(得分:0)

我认为问题在于您的代码期望.Folders属性包含所有文件夹(递归),而您只是获取根文件夹的直接子项。在第二个循环中,检查docLibrary.Folders属性/集合的上下文,看看返回的内容。