我需要在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"文件夹跳过它的创建。我该如何解决?
答案 0 :(得分:1)
尝试使用以下代码来帮助您检查sharepoint文件夹是否存在
using Microsoft.SharePoint.Client;
namespace SharePoint.Client.Extensions
{
public static class WebExtensions
{
public static bool TryGetFileByServerRelativeUrl(this Web web, string serverRelativeUrl, out File file)
{
var ctx = web.Context;
try
{
file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
ctx.Load(file);
ctx.ExecuteQuery();
return true;
}
catch (ServerException ex)
{
if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
{
file = null;
return false;
}
throw;
}
}
}
}
答案 1 :(得分:0)
更改FolderExists方法中的以下代码行
var folderRelativeUrl = string.Format("/{0}/{1}", list.RootFolder.ServerRelativeUrl, folderUrl);
到
var folderRelativeUrl = string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, folderUrl);
注意:修改" / {0} / {1}"到" {0} / {1}"