Windows 將特殊資料夾路徑 (桌面、我的文件、啟動目錄等) 儲存在登錄檔 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders。本文封裝一個 SystemPaths 類別,透過 Microsoft.Win32.RegistryKey 讀取這些路徑,提供強型別存取方法。
using System;
using Microsoft.Win32;
public class SystemPaths
{
private readonly RegistryKey _shellFolders;
public SystemPaths()
{
_shellFolders = OpenRegistryPath(
Registry.CurrentUser,
@"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders");
}
private RegistryKey OpenRegistryPath(RegistryKey root, string path)
{
// 移除開頭 '\' 並確保結尾有 '\'
path = path.TrimStart('\\') + @"\";
while (path.Contains(@"\"))
{
string segment = path.Substring(0, path.IndexOf(@"\"));
root = root.OpenSubKey(segment);
path = path.Substring(path.IndexOf(@"\") + 1);
}
return root;
}
private string GetValue(string name) => _shellFolders?.GetValue(name)?.ToString();
// 常用特殊資料夾屬性
public string Desktop => GetValue("Desktop");
public string Fonts => GetValue("Fonts");
public string NetHood => GetValue("NetHood");
public string Personal => GetValue("Personal"); // 我的文件
public string Programs => GetValue("Programs");
public string Recent => GetValue("Recent");
public string SendTo => GetValue("SendTo");
public string StartMenu => GetValue("StartMenu");
public string Startup => GetValue("Startup");
public string Favorites => GetValue("Favorites");
public string History => GetValue("History");
public string Cookies => GetValue("Cookies");
public string Cache => GetValue("Cache");
public string AppData => GetValue("AppData");
public string PrintHood => GetValue("PrintHood");
// 通用方法
public string Customize(string folderName) => GetValue(folderName);
}
var paths = new SystemPaths();
Console.WriteLine($"桌面: {paths.Desktop}");
Console.WriteLine($"我的文件: {paths.Personal}");
Console.WriteLine($"啟動目錄: {paths.Startup}");
Console.WriteLine($"應用程式資料: {paths.AppData}");
.NET Framework 2.0+ 提供 Environment.GetFolderPath,更簡單且跨平台友善:
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
建議優先使用 Environment.GetFolderPath;僅在需存取非標準資料夾或舊版 .NET 相容時,才使用登錄檔讀取。
封裝登錄檔讀取邏輯為 SystemPaths 類別,提供強型別屬性存取常用特殊資料夾,並補充說明 .NET 內建替代方案,讓開發者依專案需求選擇最適當方式。