[C#.NET][Sharepoint 2013] 如何使用 CSOM 整合 Sharepoint Server,以文件庫 CRUD 為例

[C#.NET][Sharepoint 2013] 如何使用 CSOM 整合 Sharepoint Server,以文件庫 CRUD 為例

開發前準備,

  1. http://www.microsoft.com/en-us/download/details.aspx?id=35585
  2. 加入 Microsoft.SharePoint.Client.dll & Microsoft.SharePoint.Client.Runtime.dll 參考

開發步驟:

  1. 建立 ClientContext 執行個體,需要以下條件
    1. 目的地位置,比如 http://sps2013
    2. 指訂授權帳號密碼 ClientContext.Credentials
  2. 調用 ClientContext.Load<T>
    1. 載入 client 物件,這代表查詢命令的定義
    2. 這時候的命令還不會送出
  3. 調用 ClientContext.ExecuteQuery()
    1. 會依照  ClientContext.Load 的查詢定義,送給 SHarepoint Server ,然後返回相關的物件

 

開發範例

上傳文件:

查詢文件:

刪除檔案:

 


 

上傳文件:

這是一個非常簡單的程式碼,在頂層網站的 Documents 清單裡,上傳一個檔案


private static void add()
{
    using (ClientContext client = new ClientContext("http://sps2013"))
    {
        client.Credentials = new NetworkCredential("your account", "your password");

        var site = client.Web;
        var list = site.Lists.GetByTitle("Documents");

        FileCreationInformation file = new FileCreationInformation()
        {
            Content = System.IO.File.ReadAllBytes("demo.docx"),
            Url = "demo.docx",
            Overwrite = true
        };
        var uploadingFile = list.RootFolder.Files.Add(file);

        client.Load(uploadingFile);

        client.ExecuteQuery();
    }
    Console.Read();
}

 

 

結果如下圖
image

 

查詢文件:

透過 Load 方法,將欲查詢物件倒出來


private static void read()
{
    using (ClientContext client = new ClientContext("http://sps2013"))
    {
        client.Credentials = new NetworkCredential("your account", "your password");

        var site = client.Web;
        var list = site.Lists.GetByTitle("Documents");

        var files = list.RootFolder.Files;
        client.Load(site);
        client.Load(list);
        client.Load(files);
        client.ExecuteQuery();

        Console.WriteLine("Web site's Title:{0}", site.Title);
        Console.WriteLine("List's Title:{0}", list.Title);

        foreach (var file in files)
        {
            Console.WriteLine("File Name:{0}", file.Name);
            Console.WriteLine("MajorVersion:{0}", file.MajorVersion);
        }

        Console.Read();
    }
}

 

image

 

 

 

刪除檔案:


private static void delete()
{
    using (ClientContext client = new ClientContext("http://sps2013"))
    {
        client.Credentials = new NetworkCredential("your account", "your password");
        var site = client.Web;
        var list = site.Lists.GetByTitle("Documents");

        var deleteFile = list.RootFolder.Files.GetByUrl("demo.docx");
        deleteFile.DeleteObject();
        client.ExecuteQuery();
    }
}

 


文章出自:http://www.dotblogs.com.tw/yc421206/archive/2014/06/03/145354.aspx

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo