将wpf应用程序的root作为字符串

时间:2015-06-24 10:36:31

标签: c# wpf appdomain

还有另一种方法可以将wpf应用程序的根目录作为字符串吗? 现在我还在使用

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

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

我也试过

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

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

3 个答案:

答案 0 :(得分:0)

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

另一种方式是:

Environment.CurrentDirectory 

如果没有改变。

答案 1 :(得分:0)

您可以在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");

答案 2 :(得分:0)

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

如果您从数据库中获取相对图像路径,则可以创建Pack URI并加载BitmapImage,如下所示:

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