摘要:如何動態取得系統特殊資料夾(我的文件、我的音樂......等)
好久沒寫部落格了,因為最近比較忙加上又學習新的BHT-BASIC,一直沒有時間弄這些,這些日子我也在研究軟體工程,我會把資料整理出來與大家分享。
ㄟㄟㄟ~說到哪了...回到主題,今天有網友問我要如何動態取得系統中的我的文件夾、我的圖片目錄,我告訴他怎麼做,另一方面也在這邊向大家簡單說明。
基本上我們使用兩種方法來取得系統特殊資料夾
第一種
使用My Namespaces的My.Computer.SpecialDirectories類別來實作,在這邊我也提供另一個方式來取得Temp目錄,就是使用System.IO.Path類別。
第二種
使用System.Environment類別的GetFolderPath方法,並搭配Environment.SpecialFolder列舉型別來實作。
Environment.SpecialFolder列舉型別 - 成員清單
成員名稱 | 說明 | |
---|---|---|
![]() ![]() | ApplicationData | 表示做為目前漫遊使用者的應用程式特定資料之通用儲存機制的目錄。 |
CommonApplicationData | 表示做為所有使用者使用的應用程式特定資料之通用儲存機制的目錄。 | |
LocalApplicationData | 表示做為目前非漫遊使用者使用的應用程式特定資料之通用儲存機制的目錄。 | |
Cookies | 表示做為網際網路 Cookie 通用儲存機制的目錄。 | |
Desktop | 邏輯的 [桌面],而不是實體的檔案系統位置。 | |
![]() ![]() | Favorites | 表示做為使用者的我的最愛項目之通用儲存機制的目錄。 |
History | 表示做為網際網路記錄項目通用儲存機制的目錄。 | |
InternetCache | 表示做為網際網路暫存檔通用儲存機制的目錄。 | |
![]() ![]() | Programs | 包含使用者程式群組的目錄。 |
MyComputer | [我的電腦] 資料夾。 | |
MyMusic | [我的音樂] 資料夾。 | |
MyPictures | [我的圖片] 資料夾。 | |
Recent | 包含使用者最近使用之文件的目錄。 | |
SendTo | 包含 [傳送到] 功能表項目的目錄。 | |
![]() ![]() | StartMenu | 包含 [開始] 功能表項目的目錄。 |
![]() ![]() | Startup | 對應至使用者 [啟動] 程式群組的目錄。 |
System | System 目錄。 | |
Templates | 表示做為文件樣板 (Template) 通用儲存機制的目錄。 | |
DesktopDirectory | 表示用來實際儲存桌面上檔案物件的目錄。 | |
![]() ![]() | Personal | 表示做為文件通用儲存機制的目錄。 |
MyDocuments | [我的文件] 資料夾。 | |
ProgramFiles | Program Files 目錄。 | |
CommonProgramFiles | 表示在應用程式間共享的元件的目錄。 |
詳細方法如下所示
【原始碼】 原始碼下載請按我
My.Computer.SpecialDirectories類別
01 
using Microsoft.VisualBasic.Devices;
02
//...
03
//.....
04
private void Form1_Load(object sender, EventArgs e)
05
{
06
Computer myComputer = new Computer();
07
08
//AllUsersApplicationData
09
textBox1.Text = myComputer.FileSystem.SpecialDirectories.AllUsersApplicationData;
10
//CurrentUserApplicationData
11
textBox2.Text = myComputer.FileSystem.SpecialDirectories.CurrentUserApplicationData;
12
//桌面目錄路徑
13
textBox3.Text = myComputer.FileSystem.SpecialDirectories.Desktop;
14
//我的文件夾目錄路徑
15
textBox4.Text = myComputer.FileSystem.SpecialDirectories.MyDocuments;
16
//我的音樂目錄路徑
17
textBox5.Text = myComputer.FileSystem.SpecialDirectories.MyMusic;
18
//我的圖片目錄路徑
19
textBox6.Text = myComputer.FileSystem.SpecialDirectories.MyPictures;
20
//ProgramFiles目錄路徑
21
textBox7.Text = myComputer.FileSystem.SpecialDirectories.ProgramFiles;
22
//程式集目錄路徑
23
textBox8.Text = myComputer.FileSystem.SpecialDirectories.Programs;
24
//Temp目錄 - 方法一
25
textBox9.Text = myComputer.FileSystem.SpecialDirectories.Temp;
26
//Temp目錄 - 方法二 (這個方法是直接使用System.IO.Path類別)
27
textBox10.Text = System.IO.Path.GetTempPath();
28
}


02

03

04

05


06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

System.Environment類別的GetFolderPath方法
【執行結果】