1. 程式人生 > 其它 >C#讀取“我的文件”等特殊系統路徑及環境變數

C#讀取“我的文件”等特殊系統路徑及環境變數

返回“我的文件”路徑字串

Environment.GetFolderPath(Environment.SpecialFolder.Personal)

本技巧使用GetFolderPath方法來獲取指向由指定列舉標識的系統特殊資料夾的路徑。語法格式如下:

public static string GetFolderPath (SpecialFolder folder)

引數folder標識系統特殊資料夾的列舉常數。

如果指定系統的特殊資料夾存在於使用者的計算機上,則返回到該資料夾的路徑;否則為空字串(" ")。如果系統未建立資料夾、已刪除現有資料夾或者資料夾是不對應物理路徑的虛擬目錄(例如“我的電腦”),則該資料夾不會實際存在。

主要程式碼如下:

MessageBox.Show("我的文件系統路徑:" + Environment.GetFolderPath(Environment.SpecialFolder.Personal), "我的文件",MessageBoxButtons.OK,MessageBoxIcon.Information);

參考一:C# 如何獲取某使用者的“我的文件”的目錄 Console.WriteLine(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); System.Environment.GetFolderPath 方法 獲取指向由指定列舉標識的系統特殊資料夾的路徑。 public static string GetFolderPath( Environment.SpecialFolder folder ) Environment.SpecialFolder 列舉說明: 成員名稱 說明  ApplicationData 目錄,它用作當前漫遊使用者的應用程式特定資料的公共儲存庫。  CommonApplicationData 目錄,它用作所有使用者使用的應用程式特定資料的公共儲存庫。  LocalApplicationData 目錄,它用作當前非漫遊使用者使用的應用程式特定資料的公共儲存庫。  Cookies 用作 Internet Cookie 的公共儲存庫的目錄。  Desktop 邏輯桌面,而不是物理檔案系統位置。  Favorites 用作使用者收藏夾項的公共儲存庫的目錄。  History 用作 Internet 歷史記錄項的公共儲存庫的目錄。  InternetCache 用作 Internet 臨時檔案的公共儲存庫的目錄。  Programs 包含使用者程式組的目錄。  MyComputer “我的電腦”資料夾。   MyMusic “My Music”資料夾。  MyPictures “My Pictures”資料夾。  Recent 包含使用者最近使用過的文件的目錄。  SendTo 包含“傳送”選單項的目錄。  StartMenu 包含“開始”選單項的目錄。  Startup 對應於使用者的“啟動”程式組的目錄。  System “System”目錄。  Templates 用作文件模板的公共儲存庫的目錄。  DesktopDirectory 用於物理上儲存桌面上的檔案物件的目錄。  Personal 用作文件的公共儲存庫的目錄。  MyDocuments “我的電腦”資料夾。  ProgramFiles “Program files”目錄。  CommonProgramFiles 用於應用程式間共享的元件的目錄。

參考二:C#開啟桌面等特殊系統路徑

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

using Microsoft.Win32;
namespace JPGCompact
{
    public partial class MainForm : Form
    {
        private void Test()
        {
            RegistryKey folders;
            folders = OpenRegistryPath(Registry.CurrentUser, @"softwaremicrosoftwindowscurrentversionexplorershell 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;
        }
    }

c#中讀取系統的環境變數、我的文件路徑、桌面路徑等

1 直接System.Environment.GetEnvironmentVariable["變數名"]; 比如得到計算機名、程式資料夾等 [sourcecode language='c#'] TextBox1.Text = System.Environment.GetEnvironmentVariable(“COMPUTERNAME”) +”rn”; TextBox1.Text = System.Environment.GetEnvironmentVariable(“ProgramFiles”) +”rn”; [/sourcecode]

至於像“桌面”“我的文件”可以這麼得到

[code language='C#'] TextBox1.Text += Environment.GetFolderPath(Environment.SpecialFolder.Personal)+ "rn";//我的文件 TextBox1.Text += Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "rn";//桌面 [/code] 就是用Environment.GetFolderPath(Environment.SpecialFolder.特殊資料夾) 像cookies、音樂、視訊、傳送到等等都可以這樣獲得路徑

2

C#讀取系統的環境變數

using System;using System.Collections; class ForeachApp{    public static void Main()    {        // 把環境變數中所有的值取出來,放到變數environment中        IDictionary environment = Environment.GetEnvironmentVariables();               // 打印表頭        Console.WriteLine("環境變數名t=t環境變數值");         // 遍歷environment中所有鍵值        foreach (string environmentKey in environment.Keys)        {            // 打印出所有環境變數的名稱和值            Console.WriteLine("{0}t=t{1}", environmentKey, environment[environmentKey].ToString());        }    }}

3

C#讀取設定path環境變數並重啟計算機

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;//登錄檔操作要引用的空間
using System.Runtime.InteropServices;//呼叫API函式需要的引用,來載入非託管類user32.dll

namespace 用程式修改環境變數
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        /// <summary>
        /// 讀取登錄檔
        /// path的路徑:[HKEY_LOCAL_MACHINESYSTEMControlSet001ControlSession ManagerEnvironment]
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbnRead_Click(object sender, EventArgs e)
        {
            RegistryKey regLocalMachine = Registry.LocalMachine;
            RegistryKey regSYSTEM = regLocalMachine.OpenSubKey("SYSTEM", true);//開啟HKEY_LOCAL_MACHINE下的SYSTEM
            RegistryKey regControlSet001 = regSYSTEM.OpenSubKey("ControlSet001", true);//開啟ControlSet001
            RegistryKey regControl = regControlSet001.OpenSubKey("Control", true);//開啟Control
            RegistryKey regManager = regControl.OpenSubKey("Session Manager", true);//開啟Control
            RegistryKey regEnvironment = regManager.OpenSubKey("Environment", true);//開啟MSSQLServer下的MSSQLServer
            this.richTextBox1.Text = regEnvironment.GetValue("path").ToString();//讀取path的值
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]//SendMessageTimeout是在user32.dll中定義的
        public static extern IntPtr SendMessageTimeout(
     IntPtr windowHandle,
     uint Msg,
     IntPtr wParam,
     IntPtr lParam,
     SendMessageTimeoutFlags flags,
     uint timeout,
     out IntPtr result
     );
        [Flags]
        public enum SendMessageTimeoutFlags : uint
        {
            SMTO_NORMAL = 0x0000,
            SMTO_BLOCK = 0x0001,
            SMTO_ABORTIFHUNG = 0x0002,
            SMTO_NOTIMEOUTIFNOTHUNG = 0x0008
        }
        private void btnWrite_Click(object sender, EventArgs e)
        {
            RegistryKey regLocalMachine = Registry.LocalMachine;
            RegistryKey regSYSTEM = regLocalMachine.OpenSubKey("SYSTEM", true);//開啟HKEY_LOCAL_MACHINE下的SYSTEM
            RegistryKey regControlSet001 = regSYSTEM.OpenSubKey("ControlSet001", true);//開啟ControlSet001
            RegistryKey regControl = regControlSet001.OpenSubKey("Control", true);//開啟Control
            RegistryKey regManager = regControl.OpenSubKey("Session Manager", true);//開啟Control
            RegistryKey regEnvironment = regManager.OpenSubKey("Environment", true);//開啟MSSQLServer下的MSSQLServer
            regEnvironment.SetValue("path", this.richTextBox1.Text);//讀取path的值

            MessageBox.Show("修改成功");
            //下面利用傳送系統訊息,就不要重新啟動計算機了
           const int HWND_BROADCAST=0xffff;
           // DWORD dwMsgResult = 0L;
           const uint WM_SETTINGCHANGE = 0;
           const long SMTO_ABORTIFHUNG = 0x2;
          System.UInt32 dwMsgResult1=0;
          long s;
         // SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (string)"Environment", SMTO_ABORTIFHUNG, 5000,(long)s);
        }
        /// <summary>
        /// 重新啟動計算機
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        //主要API是這個,注意:必須宣告為static extern
        private static extern int ExitWindowsEx(int x, int y);
        private void button1_Click(object sender, EventArgs e)
        {
            ExitWindowsEx(2,0);
        }
    }
}