本文記錄在 Visual Studio 2005 環境下,從零建立主控台應用程式、加入 Microsoft.SharePoint 參考、撰寫程式碼列舉站台集合下所有網站與清單數量的完整步驟,適用於早期 SharePoint 開發入門參考。
using System;
using Microsoft.SharePoint;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using (SPSite siteCollection = new SPSite("https://Server_Name"))
{
SPWebCollection webs = siteCollection.AllWebs;
foreach (SPWeb web in webs)
{
Console.WriteLine($"Site: {web.Name} Lists: {web.Lists.Count}");
web.Dispose(); // 重要:釋放非受控資源
}
}
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
}
}
}
Imports Microsoft.SharePoint
Module Module1
Sub Main()
Dim siteCollection As New SPSite("https://Server_Name")
Dim webs As SPWebCollection = siteCollection.AllWebs
For Each web As SPWeb In webs
Console.WriteLine("Site: " + web.Name + " Lists: " + web.Lists.Count.ToString())
web.Dispose()
Next
Console.WriteLine("Press ENTER to continue")
Console.ReadLine()
End Sub
End Module
| 錯誤 | 原因 | 解決 |
|---|---|---|
| FileNotFoundException | 專案目標平台為 x64,SharePoint 組件為 x86 | 專案屬性 → Build → 勾選 "Prefer 32-bit" 或明確設定 Platform target = x86 |
| SPRequest not disposed | 未呼叫 `web.Dispose()` 或 `siteCollection.Dispose()` | 使用 `using` 區塊或 `finally` 確保釋放 |
| Access Denied | 執行身分無 SharePoint 權限 | 以農場管理員/網站集合管理員身分執行,或設定 AppPool 身分 |
雖然 VS2005/SharePoint 2007 已過支援週期,但此主控台應用程式範本仍為理解 SharePoint 伺服器端物件模型(SSOM)基礎架構的最佳切入點。現代開發請改用 .NET Core + CSOM/REST API 或 SPFx。