如何通过c#代码在sharepoint中创建嵌套文件夹? 例如,我有像“共享文档/文件夹1 /文件夹2 /文件夹3”这样的字符串,我想通过c#代码创建文件夹或跳过文件夹已存在的文件夹。任何建议或代码都是高度评价的。
答案 0 :(得分:2)
internal static class SPFolderExtensions
{
/// <summary>
/// Ensure SPFolder
/// </summary>
/// <param name="web"></param>
/// <param name="listTitle"></param>
/// <param name="folderUrl"></param>
/// <returns></returns>
public static SPFolder CreateFolder(this SPWeb web, string listTitle, string folderUrl)
{
if (string.IsNullOrEmpty(folderUrl))
throw new ArgumentNullException("folderUrl");
var list = web.Lists.TryGetList(listTitle);
return CreateFolderInternal(list, list.RootFolder, folderUrl);
}
private static SPFolder CreateFolderInternal(SPList list, SPFolder parentFolder, string folderUrl)
{
var folderNames = folderUrl.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
var folderName = folderNames[0];
var curFolder =
parentFolder.SubFolders.Cast<SPFolder>()
.FirstOrDefault(
f =>
System.String.Compare(f.Name, folderName, System.StringComparison.OrdinalIgnoreCase) ==
0);
if (curFolder == null)
{
var folderItem = list.Items.Add(parentFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder,
folderName);
folderItem.SystemUpdate();
curFolder = folderItem.Folder;
}
if (folderNames.Length > 1)
{
var subFolderUrl = string.Join("/", folderNames, 1, folderNames.Length - 1);
return CreateFolderInternal(list, curFolder, subFolderUrl);
}
return curFolder;
}
}
关键点:
用法
以下示例演示如何在Documents
库下创建以下文件夹结构:
Orders
|
Orders A
|
Orders A1
示例:
var folder = web.CreateFolder("Documents", "Orders/Orders A/Orders A1");