C 獲取當前應用程式所在路徑及環境變數

2021-08-20 01:52:03 字數 2358 閱讀 5517

一、獲取當前檔案的路徑

string str1=process.getcurrentprocess().mainmodule.filename;//可獲得當前執行的exe的檔名。 

string str2=environment.currentdirectory;//獲取和設定當前目錄(即該程序從中啟動的目錄)的完全限定路徑。(備註:按照定義,如果該程序在本地或網路驅動器的根目錄中啟動,則此屬性的值為驅動器名稱後跟乙個尾部反斜槓(如「c:\」)。如果該程序在子目錄中啟動,則此屬性的值為不帶尾部反斜槓的驅動器和子目錄路徑[如「c:\mysubdirectory」])。 

string str3=directory.getcurrentdirectory(); //獲取應用程式的當前工作目錄。 

1. system.diagnostics.process.getcurrentprocess().mainmodule.filename 

獲取模組的完整路徑。

2. system.environment.currentdirectory 

獲取和設定當前目錄(該程序從中啟動的目錄)的完全限定目錄。

3. system.io.directory.getcurrentdirectory() 

獲取應用程式的當前工作目錄。這個不一定是程式從中啟動的目錄啊,有可能程式放在c:\www裡,這個函式有可能返回c:\documents and settings\zyb\,或者c:\program files\adobe\,有時不一定返回什麼東東,這是任何應用程式最後一次操作過的目錄,比如你用word開啟了e:\doc\my.doc這個檔案,此時執行這個方法就返回了e:\doc了。

獲取程式的基目錄。

獲取啟動了應用程式的可執行檔案的路徑。效果和2、5一樣。只是5返回的字串後面多了乙個"\"而已。

獲取啟動了應用程式的可執行檔案的路徑及檔名,效果和1一樣。

獲取和設定包括該應用程式的目錄的名稱。

二、操作環境變數

利用system.environment.getenvironmentvariable()方法可以很方便地取得系統環境變數,如:system.environment.getenvironmentvariable("windir")就可以取得windows系統目錄的路徑。

以下是一些常用的環境變數取值:

system.environment.getenvironmentvariable("windir");

system.environment.getenvironmentvariable("include");

system.environment.getenvironmentvariable("tmp");

system.environment.getenvironmentvariable("temp");

system.environment.getenvironmentvariable("path");

三、應用例項

編寫了乙個winform程式,專案檔案存放於d:\projects\demo,編譯後的檔案位於d:\projects\demo\bin\debug,最後的結果如下:

1、system.diagnostics.process.getcurrentprocess().mainmodule.filename=d:\projects\demo\bin\debug\demo.vshost.exe

2、system.environment.currentdirectory=d:\projects\demo\bin\debug

3、system.io.directory.getcurrentdirectory()=d:\projects\demo\bin\debug

system.environment.getenvironmentvariable("windir")=c:\windows

system.environment.getenvironmentvariable("include")=c:\program files\microsoft visual studio.net 2005\sdk\v2.0\include\

system.environment.getenvironmentvariable("tmp")=c:\docume~1\admini~1\locals~1\temp

system.environment.getenvironmentvariable("temp")=c:\docume~1\admini~1\locals~1\temp

system.environment.getenvironmentvariable("path")=c:\windows\system32;c:\windows;c:\windows\system32\wbem;c:\program files\microsoft sql server\90\tools\binn\

**:

c 獲取當前應用程式所在路徑

二 操作環境變數 利用system.environment.getenvironmentvariable 方法可以很方便地取得系統環境變數,如 system.environment.getenvironmentvariable windir 就可以取得windows系統目錄的路徑。以下是一些常用的環...

c 獲取當前應用程式所在路徑

2.c winform用 d system.threading.thread.getdomain basedirectory 獲取當前應用程式所在目錄的路徑,最後包含 e environment.currentdirectory 獲取當前應用程式的路徑,最後不包含 f system.io.direc...

C 獲取當前應用程式所在的路徑

1.system.diagnostics.process.getcurrentprocess mainmodule.filename 獲取模組的完整路徑,可獲得當前執行的exe的檔名。2.system.environment.currentdirectory 獲取和設定當前目錄 該程序從中啟動的目錄...