1. 程式人生 > >C#獲取桌面等特殊資料夾的路徑

C#獲取桌面等特殊資料夾的路徑

C#獲取桌面路徑

不同的作業系統,桌面的路徑不盡相同,而且隨著使用者安裝位置的不同也不同。C#可以從Windows登錄檔讀取得到使用者的特殊資料夾(桌面、收藏夾等等)的位置。
程式碼如下:

法一:

string desktop=Environment.GetFolderPath(Environment.SpecialFolder.Desktop);//桌面路徑 

法二:

using Microsoft.Win32;
namespace JPGCompact
{
    public partial class MainForm : Form
    {
        private void Test()
        {
          RegistryKey folders;
          folders = OpenRegistryPath(Registry.CurrentUser, @"\software\microsoft\windows\currentversion\explorer\shell folders");
            // Windows使用者桌面路徑
            string desktopPath = folders.GetValue("Desktop").ToString();
            // Windows使用者字型目錄路徑
            string fontsPath = folders.GetValue("Fonts").ToString();
            // Windows使用者網路鄰居路徑
            string nethoodPath = folders.GetValue("Nethood").ToString();
            // Windows使用者我的文件路徑
            string personalPath = folders.GetValue("Personal").ToString();
            // Windows使用者開始選單程式路徑
            string programsPath = folders.GetValue("Programs").ToString();
            // Windows使用者存放使用者最近訪問文件快捷方式的目錄路徑
            string recentPath = folders.GetValue("Recent").ToString();
            // Windows使用者傳送到目錄路徑
            string sendtoPath = folders.GetValue("Sendto").ToString();
            // Windows使用者開始選單目錄路徑
            string startmenuPath = folders.GetValue("Startmenu").ToString();
            // Windows使用者開始選單啟動項目錄路徑
            string startupPath = folders.GetValue("Startup").ToString();
            // Windows使用者收藏夾目錄路徑
            string favoritesPath = folders.GetValue("Favorites").ToString();
            // Windows使用者網頁歷史目錄路徑
            string historyPath = folders.GetValue("History").ToString();
            // Windows使用者Cookies目錄路徑
            string cookiesPath = folders.GetValue("Cookies").ToString();
            // Windows使用者Cache目錄路徑
            string cachePath = folders.GetValue("Cache").ToString();
            // Windows使用者應用程式資料目錄路徑
            string appdataPath = folders.GetValue("Appdata").ToString();
            // Windows使用者列印目錄路徑
            string printhoodPath = folders.GetValue("Printhood").ToString();
        }

        private RegistryKey OpenRegistryPath(RegistryKey root, string s)
        {
            s = s.Remove(0, 1) + @"\";
            while (s.IndexOf(@"\") != -1)
            {
                root = root.OpenSubKey(s.Substring(0, s.IndexOf(@"\")));
                s = s.Remove(0, s.IndexOf(@"\") + 1);
            }
            return root;
        }
    }
}