How do I get the application's directory from my WPF application, at design time?

luvieere picture luvieere · Nov 27, 2009 · Viewed 7.2k times · Source

How do I get the application's directory from my WPF application, at design time? I need to access a resource in my application's current directory at design time, while my XAML is being displayed in the designer. I'm not able to use the solution specified in this question as at design time both System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) and System.Reflection.Assembly.GetExecutingAssembly().Location point to the IDE's location (Visual Studio... Common7 or something).

Upon request to further clarify my goals: I want to access a database table at design time and display a graphic of that data. The design is done in Visual Studio 2008, so what I need is a very specific solution to a very specific problem, and that is getting the assembly directory for my app.

Answer

Ray Burns picture Ray Burns · Jan 21, 2010

From your description it sounds like your code is actually running inside the WPF Designer within Visual Studio, for example it is part of a custom control library that is being used for design.

In this case, Assembly.GetEntryAssembly() returns null, but the following code gets the path to the application directory:

  string applicationDirectory = (
    from assembly in AppDomain.CurrentDomain.GetAssemblies()
    where assembly.CodeBase.EndsWith(".exe")
    select System.IO.Path.GetDirectoryName(assembly.CodeBase.Replace("file:///", ""))
    ).FirstOrDefault();

The following steps can be used to demonstrate this works inside VS.NET 2008's WPF Designer tool:

  1. Place this code inside a "WPF Custom Control Library" or "Class Library" project
  2. Add whatever code is necessary to read the database and return the data for display (in my case I just returned the application directory itself as a string)
  3. Reference the library project from the project you are designing
  4. Use the custom controls or classes from a XAML file to populate your DataContext or otherwise supply data to your UI (in my case I bound DataContext using x:Static)
  5. Edit that XAML file with the "Windows Presentation Foundation Designer", which can be done by just double-clicking unless you have changed your default editor, in which case use "Open With..."

When you follow these steps, the object you are looking at will be populated with data from your database the same way both at run time and design time.

There are other scenarios in which this same technique works just as well, and there are other solutions available depending on your needs. Please let us know if your needs are different those I assumed above. For example, if you are writing a VS.NET add-in, you are in a completely different ball game.