getting root of wpf app as a string

661 Views Asked by At

Is there another way to get the root of a wpf application as a string? Now I'm still using

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

This gives me the root as a string, but I assume this is not the right way to do it.

I also tried

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

but this sends me to root/bin/debug. I only need the root as a string

3

There are 3 best solutions below

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

Another way is:

Environment.CurrentDirectory 

if it was not changed.

0
On

You can find the file path of the root folder of the startup project in a WPF App like this:

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

Or to complete your example by getting the file path of the parent folder of the parent folder, you can do this:

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

UPDATE >>>

In order to access your project Images folder, you can do this:

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

You should put the images in a folder of your Visual Studio project called "Images" and set their Build Action to Resource (as shown here).

If you then get a relative image path from your DB, you would create a Pack URI and load a BitmapImage like this:

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