Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Working Directory

Tags:

wpf

I have a WPF application that gets installed on the client machine through the Windows Installer. This application also registers a file extension (.xyz), so when the user double clicks a file, it opens my WPF application and displays the file (like Microsoft Word). This program also has a ton of files that are not marked as resource or content files that it uses (user manuals, part drawings, etc).

The problem comes when the user double clicks a .xyz file and it opens the WPF application. The application now has a working directory of the directory where the .xyz file is located. Now the program cannot find any of the files (user manuals, part drawings, etc) it needs.

What is the best way to handle this type of problem? I could set the working directory (Environment.CurrentDirectory), but my open file dialog box changes the working directory when the user saves or opens an .xyz file. I could use a pack uri for the part drawings, but I use Process.Start for the user manuals because they are a PDF. I tried searching, but couldn't come up with anyting.

like image 231
awilinsk Avatar asked Jun 18 '10 12:06

awilinsk


2 Answers

You should be able to get to your install directory either by finding the executable's directory or by using reflection to find an assemly's directory:

By finding executable, you could add a reference to Windows.Forms to make this work (admittedly not ideal):

using System.IO;
using System.Windows.Forms;

string appPath = Path.GetDirectoryName(Application.ExecutablePath);

Using reflection:

using System.IO;
using System.Reflection;

string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).CodeBase);

Or

string path = System.Reflection.Assembly.GetExecutingAssembly().Location;

You can probably just cache that path onload of your app as it will not change.

like image 183
brendan Avatar answered Sep 29 '22 17:09

brendan


There's a difference between the location of the Assembly and the working directory of the application. Sometimes these might be the same, but this must not be the case. To change the working directory you can execute your application from cmd.exe or just create a shortcut with a different directory in the Start in Property.

You can get the working directory of the Application like this:

System.IO.Path.GetFullPath(".")

Note: The .-Directory is always the current working Directory, we just get the absolute path to it. Sometimes you might not need the absolute path. For example if you want to read a file in the working directory:

new StreamReader("./file-in-the-working-directory.txt");

or even:

new StreamReader("file-in-the-working-directory.txt");
like image 37
MarcDefiant Avatar answered Sep 29 '22 19:09

MarcDefiant