Jun*_*ior 9 c# sharepoint office365 csom
我使用CSOM在C#中编码,我的应用程序将模板asp.net页面上传到"/ Pages /"库,我需要它在文件上传之前检查该位置是否存在同名的文件(然后可能它可以返回一个bool值).
我确实快速浏览了一下,但我发现的大多数解决方案都提到了使用Javascript,或者应用于本地部署.
如果有人能指出我正确的方向,我会很感激.
Vad*_*hev 15
您可以考虑以下方法来确定文件是否存在.
您可以构建CAML查询以通过其Url查找列表项,如下所示:
public static bool FileExists(List list, string fileUrl)
{
var ctx = list.Context;
var qry = new CamlQuery();
qry.ViewXml = string.Format("<View Scope=\"RecursiveAll\"><Query><Where><Eq><FieldRef Name=\"FileRef\"/><Value Type=\"Url\">{0}</Value></Eq></Where></Query></View>",fileUrl);
var items = list.GetItems(qry);
ctx.Load(items);
ctx.ExecuteQuery();
return items.Count > 0;
}
Run Code Online (Sandbox Code Playgroud)
用法
using (var ctx = GetSPOContext(webUri,userName,password))
{
var list = ctx.Web.Lists.GetByTitle(listTitle);
if(FileExists(list,"/documents/SharePoint User Guide.docx"))
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
Web.GetFileByServerRelativeUrl 方法使用Web.GetFileByServerRelativeUrl方法返回位于指定服务器相对URL的文件对象.
如果file不存在,则会遇到异常Microsoft.SharePoint.Client.ServerException:
public static bool TryGetFileByServerRelativeUrl(Web web, string serverRelativeUrl,out Microsoft.SharePoint.Client.File file)
{
var ctx = web.Context;
try{
file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
ctx.Load(file);
ctx.ExecuteQuery();
return true;
}
catch(Microsoft.SharePoint.Client.ServerException ex){
if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
{
file = null;
return false;
}
else
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
using (var ctx = GetSPOContext(webUri,userName,password))
{
Microsoft.SharePoint.Client.File file;
if(TryGetFileByServerRelativeUrl(ctx.Web,"/documents/SharePoint User Guide.docx",out file))
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
Web.GetFileByServerRelativeUrl(上面发布的@vadim)的替代方法是Load(checkFile, p => p.Exists);并且在上下文中......
using (ClientContext ctx = new ClientContext("https://yoursubdomainhere.sharepoint.com/"))
{
Web web = ctx.Web;
Microsoft.SharePoint.Client.File checkFile = web.GetFileByServerRelativeUrl("/sites/Documents/MyFile.docx");
ctx.Load(checkFile, fe => fe.Exists);
ctx.ExecuteQuery();
if (!checkFile.Exists)
{
//Do something here
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Client OM,如果该文件不存在,它实际上会抛出异常:
using(var clientContext = new ClientContext(site))
{
Web web = clientContext.Web;
Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl("/site/doclib/folder/filename.ext");
bool bExists = false;
try
{
clientContext.Load(file);
clientContext.ExecuteQuery(); //Raises exception if the file doesn't exist
bExists = file.Exists; //may not be needed - here for good measure
}
catch{ }
if (bExists )
{
.
.
}
}
Run Code Online (Sandbox Code Playgroud)