2009-05-19 35 views
8

我想我的应用程序一样的路径:“\\ \\ PROGRAMFILES对myApp”,我尝试使用下面的代码:如何获取应用程序的路径(没有app.exe)?


string path = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase; 

但它返回一个具有“\\ MyApp.exe的路径“ 最后。

我也试过:


string path = System.IO.Directory.GetCurrentDirectory(); 

但它抛出一个“NotSupportedException异常”。

有没有办法在最后得到没有.exe的路径?

回答

9
path = System.IO.Path.GetDirectoryName(path); 
18

Application.StartupPath应该为你做。

更新:从你编辑我看到你在Compact Framework上运行。然后Application.StartupPath将不起作用。这是我平时那么使用结构:

private static string GetApplicationPath() 
{ 
    return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); 
} 
+0

很抱歉的混乱和感谢您的快速回答; P – 2009-05-19 08:10:07

1

您可以使用通过你的原始路径字符串作为参数,这个Path.GetDirectoryName(string)方法。你想解决什么问题?也许你真的需要像工作目录这样的东西?

+0

谢谢您和danbyStrom,您的向导效果很好。我试图在我的应用程序目录中使用wav文件播放声音,所以我需要它的目录(没有app.exe)。 – 2009-05-19 07:07:15

0
Path.GetFileNameWithoutExtension(path); 
+0

谢谢,但是这将返回文件名称“myApp”,就像方法名称中提到的一样。无论如何感谢这个方法的指导。 – 2009-05-19 06:55:32

+0

Shucks!这就是我认为你想要的。 :) – 2009-05-19 07:03:10

0

如何使用FileInfo对象来提取目录名?

在Vb.Net:

fi = New FileInfo(System.Reflection.Assembly.GetExecutingAssembly.Location) 
path = fi.DirectoryName 
+0

在C#应用程序中找不到“位置”,但()中的所有内容均可由我编写的文件路径替换,并且可以工作。谢谢。 – 2009-05-19 07:03:02

0

如果它的exe文件,你的情况使用:比其他

// Summary: 
    //  Gets the path for the executable file that started the 
    //  application, not including the executable name.  
    Application.StartupPath 
3

更简单:

using System.IO; 
using System.Reflection; 
... 
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) 
相关问题