【问题标题】:C# CSOM - Check if File Exists in Document LibraryC# CSOM - 检查文档库中是否存在文件
【发布时间】:2015-03-11 01:37:02
【问题描述】:

我正在使用 CSOM 在 C# 中编码,我的应用程序将模板 asp.net 页面上传到“/Pages/”库,我需要它在文件上传之前检查该位置是否存在同名文件(那么也许它可以返回一个布尔值)。

我确实快速浏览了一下,但我发现的大多数解决方案都提到了 Javascript 的使用,或者应用于本地部署。

如果有人能指出我正确的方向,我将不胜感激。

【问题讨论】:

    标签: c# sharepoint office365 csom


    【解决方案1】:

    您可以考虑以下方法来确定文件是否存在。

    基于查询

    您可以构造 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;
    }
    

    用法

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

    Web.GetFileByServerRelativeUrl方法

    使用 Web.GetFileByServerRelativeUrl Method 返回位于指定服务器相对 URL 的文件对象。

    如果文件不存在,将遇到异常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;
            }
        }
    

    用法:

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

    【讨论】:

    • 基于查询的解决方案完美运行。两者之间 - 有什么区别?你为什么要使用一个而不是另一个?再次感谢!
    • 我也更喜欢基于查询的方法而不是第二种方法。但在某些情况下,您可以从性能角度使用第二种方法获得好处
    • 对于 Web.GetFileByServerRelativeUrl 方法,请注意,如果您的站点位于 url 顶部下方的文件夹级别,您可能需要指定的不仅仅是“/documents/doc.docx”。我必须在主机名之后指定所有内容...例如“/sites/dept/hr/subsitename/documents/doc.docx”
    【解决方案2】:

    如果您使用的是 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

    【讨论】:

      【解决方案3】:

      Web.GetFileByServerRelativeUrl(上面发布的@vadim)的替代方法是Load(checkFile, p =&gt; 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
          }
      }
      

      【讨论】:

      • 同意。通常破坏检查的实际上是 ctx.Load(file) 因为如果文件对象不存在则无法加载。您只需加载 Exists 属性即可。
      • 尝试了这种方法,我得到了Exists 属性,对于有效和无效的文件名没有任何例外。
      • 效果很好。我认为这是最好的答案,因为它没有像其他人在这里建议的那样使用任何盲目的异常陷阱。
      【解决方案4】:

      使用 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;
      
              }
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-10
        • 1970-01-01
        • 2011-09-23
        • 2020-10-12
        • 1970-01-01
        • 2011-04-07
        • 2012-01-08
        相关资源
        最近更新 更多