2010-04-07 59 views
13

我需要在我的應用程序運行的路徑(不是可執行文件)來源:應用程序從哪裏運行的可執行目錄?

System.AppDomain.CurrentDomain.BaseDirectory() 

當我運行我的本地機器上&「/images/image.jpg」上面的語句,它工作正常但是當我在另一臺機器上安裝應用程序時,它說它找不到該文件,並且有一些額外的路徑信息。

我只需要運行應用程序的目錄。我使用Visual Studio 2008編寫VB.NET。

謝謝!

+0

不太瞭解vs 2008,但是當你做一個dirinfo時,你沒有從應用程序中獲取dirinfo。在跑? – Grumpy 2010-04-07 14:59:32

+0

可能重複的[獲取程序路徑?](http://stackoverflow.com/questions/2216141/get-programs-path) – 2016-07-10 17:03:22

回答

26
Dim strPath As String = System.IO.Path.GetDirectoryName(_ 
    System.Reflection.Assembly.GetExecutingAssembly().CodeBase) 

HOW TO: Determine the Executing Application's Path (MSDN)

+6

strPath包含**文件**:\\ c:\\ xxxxxx – Kraken101 2014-03-27 13:13:37

+0

這是不安全的,例如,當它用於打開配置文件時,會導致System.Configuration.ConfigurationErrorsException:加載配置文件時發生錯誤: URI格式不支持 – 2016-11-10 03:28:28

+0

MrCalvin的答案在這種情況下工作正常 – 2016-11-10 03:31:38

0

你可以寫:

Path.Combine(Path.GetParentDirectory(GetType(MyClass).Assembly.Location), "Images\image.jpg") 
+1

這種方法有一些缺陷,因爲程序集不一定和執行文件駐留在同一個目錄中部件。 – 2011-02-15 14:25:26

4

兩者你可以使用應用程序類的靜態StartupPath財產。

12
Dim P As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase) 
P = New Uri(P).LocalPath 
20

這是谷歌的第一篇文章,所以我想我會發布不同的方式,可用和他們如何比較。不幸的是我無法弄清楚如何在這裏創建表格,所以它是一個圖像。每個代碼都使用完全限定名稱在圖像下方。

enter image description here

My.Application.Info.DirectoryPath 

Environment.CurrentDirectory 

System.Windows.Forms.Application.StartupPath 

AppDomain.CurrentDomain.BaseDirectory 

System.Reflection.Assembly.GetExecutingAssembly.Location 

System.Reflection.Assembly.GetExecutingAssembly.CodeBase 

New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase) 

Path.GetDirectoryName(Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path))) 

Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path)) 
6

我需要知道這一點,來到了這裏,我纔想起了環境類。

如果其他人有這個問題,只需使用這個:Environment.CurrentDirectory

例子:

Dim dataDirectory As String = String.Format("{0}\Data\", Environment.CurrentDirectory) 

當從Visual Studio在調試模式下運行yeilds:

C:\Development\solution folder\application folder\bin\debug 

這是確切的行爲我需要的,其簡單明瞭就好了。

+1

最小,最簡單的解決方案,格式化! +1,謝謝。 – rdtsc 2017-01-19 20:17:16

+0

是的,這有助於通過將設置文件保存在應用程序的根路徑中來使應用程序真正具有可移植性。感謝您的簡單解決方案! – 2018-02-24 14:41:23

相關問題