如何获取应用程序的路径(不包括app.exe)?

8
我希望获得我应用程序的路径,例如: "\\ProgramFiles\\myApp"。我尝试使用以下代码:

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

但它返回的路径末尾带有“\\myapp.exe”。

我还尝试过:


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

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

有没有办法获得没有“.exe”结尾的路径?

7个回答

19

Application.StartupPath可以为您完成这个任务。

更新:从您的编辑中我看到您正在运行Compact Framework。那么Application.StartupPath将无法工作。这是我通常使用的结构:

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

11
path = System.IO.Path.GetDirectoryName( path );

3
比其他的更简单:

比其他选项更加简单易用:

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

嗯...这很简单,但是“位置”在Windows Mobile应用程序中找不到。 - Chilly Zhong

1
你可以使用 Path.GetDirectoryName(string) 方法,将原始路径字符串作为参数传递进去。你想要解决什么问题?也许你真正需要的是工作目录?

感谢您和danbyStrom,您的指南非常有效。我正在尝试在应用程序目录中使用wav文件播放声音,因此我需要它的目录(不带app.exe)。 - Chilly Zhong

0

使用FileInfo对象提取目录名称怎么样?

在VB.Net中:

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

在C#应用程序中找不到"Location",但是括号中的所有内容可以替换为我写的文件路径,它可以工作。谢谢。 - Chilly Zhong
GetExecutingAssembly 需要 () 吗?例如 GetExecutingAssembly(),还是只有 C# 这样做? - Momoro

0
如果是像你的情况一样的exe文件,请使用:
    // Summary:
    //     Gets the path for the executable file that started the 
    //     application, not including the executable name.    
    Application.StartupPath

0
Path.GetFileNameWithoutExtension(path);

谢谢,但这将返回文件名“myApp”,就像方法名所提到的那样。无论如何,感谢您对此方法的指导。 - Chilly Zhong
糟糕!这就是我认为你想要的。 :) - JP Alioto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接