以字符串形式获取wpf-app的根



是否有其他方法可以将wpf应用程序的根作为字符串获取?现在我仍在使用

string path = AppDomain.CurrentDomain.BaseDirectory.Substring(0, (AppDomain.CurrentDomain.BaseDirectory.Length - 10));

这给了我一个字符串的根,但我认为这不是正确的方法

我也试过

string txt = System.AppDomain.CurrentDomain.BaseDirectory.ToString();

但这会将我发送到root/bin/debug。我只需要根作为字符串

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

另一种方式是:

Environment.CurrentDirectory 

如果不改变的话。

您可以在WPF应用程序中找到启动项目根文件夹的文件路径,如下所示:

string applicationDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string rootPath = Directory.GetParent(applicationDirectory).Parent.FullName;

或者通过获取父文件夹的父文件夹的文件路径来完成您的示例,您可以这样做:

string rootPath = Directory.GetParent(txt).Parent.FullName;

更新>>>

为了访问您的项目Images文件夹,您可以执行以下操作:

Path.Combine(Directory.GetParent(applicationDirectory).Parent.FullName, "Images");

您应该将图像放在Visual Studio项目的一个名为"images"的文件夹中,并将其"构建操作"设置为Resource(如图所示)。

如果你从数据库中得到一个相对的图像路径,你会创建一个Pack URI并加载一个BitmapImage,如下所示:

var imagePath = "Images/SomeImage.jpg"; // actually from DB
var uri = new Uri("pack://application:,,,/" + imagePath);
var bitmap = new BitmapImage(uri);

最新更新