**僅限 Internet Explorer / Edge IE 模式**。現代瀏覽器 (Chrome、Firefox、Edge Chromium) **完全不支援 ActiveX**,因安全沙箱禁止網頁存取本地檔案系統。適用於:企業內網舊系統、IE 強制環境、特定產業軟體 (銀行、稅務、ERP)。新專案請改用 `` (資料夾上傳) 或瀏覽器擴充功能/桌面應用協助。
[C# Class Library] → [COM Visible + GUID] → [RegAsm /regserver 註冊] → [.dll + .tlb]
↓
[HTML 頁面] → → [JS 呼叫 GetDirPath()]
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms; // 需參考 System.Windows.Forms
namespace WebDirSelector
{
[ComVisible(true)]
[Guid("YOUR_GENERATED_GUID_HERE")] // 必須固定 GUID,Tools → Create GUID
[InterfaceType(ComInterfaceType.InterfaceIsDual)] // 支援早期/晚期繫結
public interface IDirSelector
{
string GetDirPath(); // 唯一對外方法
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("ANOTHER_FIXED_GUID")]
[ProgId("WebDirSelector.DirSelector")] // 供 JS new ActiveXObject 使用
public class DirSelector : IDirSelector
{
public string GetDirPath()
{
using (var dlg = new FolderBrowserDialog
{
Description = "請選擇資料夾",
ShowNewFolderButton = true,
RootFolder = Environment.SpecialFolder.MyComputer
})
{
if (dlg.ShowDialog() == DialogResult.OK)
return dlg.SelectedPath;
}
return string.Empty;
}
}
}
regasm.exe /codebase /tlb WebDirSelector.dll
**權限提示**:IE 預設阻擋未簽名 ActiveX。需:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE10" /> <!-- 強制 IE 模式 -->
</head>
<body>
<!-- classid 為 C# 類別的 Guid -->
<object id="dirSelector" classid="clsid:ANOTHER_FIXED_GUID" style="display:none;"></object>
<input type="text" id="txtPath" readonly style="width:400px;" />
<button onclick="selectFolder()">選擇資料夾</button>
<script>
function selectFolder() {
try {
var obj = document.getElementById("dirSelector");
var path = obj.GetDirPath(); // 呼叫 COM 方法
if (path) document.getElementById("txtPath").value = path;
else alert("未選擇資料夾");
} catch (ex) {
alert("ActiveX 載入失敗:" + ex.message + "\n請確認已註冊並加入信任網站。");
}
}
</script>
</body>
</html>
| 現象 | 原因與解決 |
|---|---|
| 「自動化伺服器無法建立物件」 | 1. 未註冊 (`regasm /codebase`) 2. 位元數不符 (x86 DLL 在 64 位 IE) 3. `classid` GUID 錯誤 4. IE 安全等級阻擋 → 信任網站設定 |
| 對話框不顯示/卡死 | 1. `FolderBrowserDialog` 需 STA 執行緒,ActiveX 單元模型預設 STA,通常無問題。 2. 若在非 UI 執行緒呼叫,需 `Thread.SetApartmentState(ApartmentState.STA)`。 3. 伺服器端開發機測試正常,客戶端失敗 → 檢查 `ShowDialog()` 父視窗控制代碼 (可傳 `IntPtr.Zero`)。 |
| 路徑包含中文亂碼 | C# 回傳 Unicode 字串,JS 接收為 UTF-16,正常。若經 ASP.NET 後端轉存,確保資料庫/檔案編碼為 UTF-8。 |
| 方案 | 支援瀏覽器 | 實作難度 | 備註 |
|---|---|---|---|
| `` | Chrome/Edge/Firefox/Safari (全支援) | 極低 | 回傳 FileList,可遍歷 `webkitRelativePath` 重建資料夾結構,上傳至伺服器 |
| File System Access API (`window.showDirectoryPicker()`) | Chrome 86+/Edge 86+ (安全源 HTTPS) | 低 | 真正的資料夾選擇器,回傳 `FileSystemDirectoryHandle`,可讀寫本地檔案 (需使用者授權) |
| 瀏覽器擴充功能 + Native Messaging | 全瀏覽器 | 中 | 擴充功能呼叫原生宿主程式 (C#/Go/Rust) 選擇資料夾回傳路徑 |
| 桌面應用 (WPF/WinForms/Electron/Tauri) 協同 | 無瀏覽器限制 | 高 | 註冊自定義 URI Scheme (`myapp://select-folder`),網頁跳轉喚起桌面應用 |
ActiveX 資料夾選擇器是 **IE 時代的產物**,開發流程:**C# COM Visible 類別 → 固定 GUID → RegAsm 註冊 → HTML `