2010-04-07 61 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

相关问题