SharePoint - 資料



本章將介紹SharePoint中最常見的任務之一:與各種資料來源(例如列表或文件庫)互動。SharePoint的一大優點是您可以使用多種選項與資料互動。例如,伺服器物件模型、客戶端物件模型、REST服務等。

在以程式設計方式操作SharePoint之前,您需要與SharePoint網站建立連線和上下文。但是,這需要本地SharePoint,可以安裝在Windows伺服器上。

您需要在專案中新增對Microsoft.SharePoint.dllMicrosoft.SharePoint.Client.dll的引用。將相應的引用新增到專案後,您就可以開始設定上下文並在該上下文中編寫程式碼。

讓我們來看一個簡單的例子。

步驟1 - 開啟Visual Studio,並從檔案→新建→專案選單選項建立一個新專案。

步驟2 - 在左側窗格中選擇模板→Visual C#下的Windows,然後在中間窗格中選擇控制檯應用程式。輸入專案的名稱,然後單擊確定。

步驟3 - 建立專案後,在解決方案資源管理器中右鍵單擊該專案,然後選擇新增→引用

Console Application

步驟4 - 在左側窗格中選擇程式集→擴充套件,然後在中間窗格中選中Microsoft.SharePoint,然後單擊確定。

現在再次在解決方案資源管理器中右鍵單擊該專案,然後選擇屬性。

Assemblies

步驟5 - 單擊左側窗格中的生成選項卡,然後取消選中首選32位選項。

Build Tab

步驟6 - 現在返回Program.cs檔案,並將其替換為以下程式碼。

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SharePointData {
   class Program {
      static void Main(string[] args) {
         using (var site = new SPSite("http://waqasserver/sites/demo")) {
            var web = site.RootWeb;
            Console.WriteLine(web.Title);
            var lists = web.Lists;
            
            foreach (SPList list in lists) {
               Console.WriteLine("\t" + list.Title);
            }
            Console.ReadLine();
         }
      }
   }
}

注意 - 上述程式碼首先建立了一個新的SPSite物件。這是一個可處置的物件,因此它是在using語句中建立的。SPSite建構函式接收網站集的URL,在您的情況下這將有所不同。

var web = site.RootWeb將獲取網站集的根。

我們可以使用web.Lists獲取列表並列印列表項的標題。

編譯並執行上述程式碼後,您將看到以下輸出:

SharePoint Tutorials
   appdata
   Composed Looks
   Documents
   List Template Gallery
   Master Page Gallery
   Site Assets
   Site Pages
   Solution Gallery
   Style Library
   Theme Gallery
   User Information List
   Web Part Gallery
廣告