简体   繁体   English

C# CSOM - 检查文档库中是否存在文件

[英]C# CSOM - Check if File Exists in Document Library

I'm coding in C# using CSOM, my app uploads a template asp.net page to the "/Pages/" library, I need it to check if a file exists in that location with the same name prior to file upload (then maybe it can return a bool value).我正在使用 CSOM 在 C# 中编码,我的应用程序将模板 asp.net 页面上传到“/Pages/”库,我需要它在文件上传之前检查该位置是否存在同名文件(然后也许它可以返回一个布尔值)。

I did have a quick look but the majority of the solutions I found referred to the use of Javascript, or applied to on-prem deployments.我确实快速浏览了一下,但我发现的大多数解决方案都涉及 Javascript 的使用,或应用于本地部署。

If someone could please point me in the right direction I would appreciate it.如果有人能指出我正确的方向,我将不胜感激。

You could consider the following approaches to determine whether file exists or not. 您可以考虑以下方法来确定文件是否存在。

Query based 基于查询

You could construct CAML query to find list item by its Url as demonstrated below: 您可以构建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;
}

Usage 用法

using (var ctx = GetSPOContext(webUri,userName,password))
{
     var list = ctx.Web.Lists.GetByTitle(listTitle);
     if(FileExists(list,"/documents/SharePoint User Guide.docx"))
     {
          //...
     }
}

Web.GetFileByServerRelativeUrl Method Web.GetFileByServerRelativeUrl方法

Use Web.GetFileByServerRelativeUrl Method to return the file object located at the specified server-relative URL. 使用Web.GetFileByServerRelativeUrl方法返回位于指定服务器相对URL的文件对象。

If file does not exists the exception Microsoft.SharePoint.Client.ServerException will be encountered: 如果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;
        }
    }

Usage: 用法:

 using (var ctx = GetSPOContext(webUri,userName,password))
 {
      Microsoft.SharePoint.Client.File file;
      if(TryGetFileByServerRelativeUrl(ctx.Web,"/documents/SharePoint User Guide.docx",out file))
      {
          //...
      }
 }    

if you are using Client OM, it would actually throw an exception if the file doesn't exist: 如果您使用的是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 )
     {
           .
           .
     }
}

Resource 资源

Using Linq To SharePoint 使用Linq To SharePoint

    public bool FolderExists(string library, string name) {

        using (var ctx = SPStatic.Context(_sharePointSiteUrl)) {

            List sharedDocs = ctx.Web.Lists.GetByTitle(library);

            var query = ctx.LoadQuery(sharedDocs.RootFolder.Folders.Where(fd => fd.Name == name));

            ctx.ExecuteQuery();

            Folder f = query.SingleOrDefault();

            return f != null;

        }

    }

An alternative to the Web.GetFileByServerRelativeUrl (@vadim posted above) is Load(checkFile, p => p.Exists); Web.GetFileByServerRelativeUrl(上面发布的@vadim)的替代方法是Load(checkFile, p => p.Exists); and in context ... 并在上下文中......

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
    }
}

There is also a client-callable Web.GetFileByUrl(string absOrServerRelUrl) functioning identically to Web.GetFileByServerRelativeUrl|Path , but returning a File object with Exist=false (while the others throw explicitly) if the file does not exist.还有一个客户端可调用的Web.GetFileByUrl(string absOrServerRelUrl)功能与Web.GetFileByServerRelativeUrl|Path相同,但如果文件不存在,则返回 Exist=false 的文件 object(而其他文件则明确抛出)。 They all call SPWeb.GetFile internally (which is not client-callable), check via ILSpy.他们都在内部调用SPWeb.GetFile (不是客户端可调用的),通过 ILSpy 检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM