如果在SharePoint文档库中不存在某个文件夹,则我需要创建该文件夹,然后将文件上传至其中。 以下是我正在使用的代码:
public static bool FolderExists(Web web, string listTitle, string folderUrl)
{
var list = web.Lists.GetByTitle(listTitle);
var folders = list.GetItems(CamlQuery.CreateAllFoldersQuery());
web.Context.Load(list.RootFolder);
web.Context.Load(folders);
web.Context.ExecuteQuery();
var folderRelativeUrl = string.Format("/{0}/{1}", list.RootFolder.ServerRelativeUrl, folderUrl);
return Enumerable.Any(folders, folderItem => (string)folderItem["FileRef"] == folderRelativeUrl);
}
private static void CreateFolder(Web web, string listTitle, string folderName)
{
var list = web.Lists.GetByTitle(listTitle);
var folderCreateInfo = new ListItemCreationInformation
{
UnderlyingObjectType = FileSystemObjectType.Folder,
LeafName = folderName
};
var folderItem = list.AddItem(folderCreateInfo);
folderItem.Update();
web.Context.ExecuteQuery();
}
public void UploadFile(string CourseId, string path)
{
string libraryName = "Documents";
using (ClientContext clientContext = GetContextObject())
{
// if a folder doesn't exists, create it
if (!FolderExists(clientContext.Web, libraryName, CourseId))
{
CreateFolder(clientContext.Web, libraryName, CourseId);
}
// if exists, upload input file in Documents/FolderName given by CourseId
Web web = clientContext.Web;
List list3 = clientContext.Web.Lists.GetByTitle("Documents");
clientContext.Load(list3.RootFolder);
clientContext.ExecuteQuery();
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
string ext = Path.GetExtension(fileStream.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, list3.RootFolder.ServerRelativeUrl.ToString() + "/" + CourseId + "/" + path.Split('\\').Last(), fileStream, true);
}
}
}
问题如下:这些函数很好用,但如果文件夹已经存在,则尝试再次创建它会导致异常,而应该只上传文件到“CourseId”文件夹并跳过其创建。我该如何解决?