首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 透過登錄檔取得系統特殊資料夾路徑:桌面、我的文件、啟動目錄等

     編輯:關於C語言

前言

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 內建方式

.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 內建替代方案,讓開發者依專案需求選擇最適當方式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved