Where Did My StartupPath Go?





5.00/5 (3 votes)
Where did my StartupPath go?
So somebody has just asked where Application.StartupPath
has disappeared in WPF. This is available in Windows Forms, but not available in WPF. A common technique to get the startup path is to use Assembly.GetEntryAssembly().Location
, but there's a problem with GetEntryAssembly
if your app is fired off from an unmanaged application, such as a COM application for instance.
We have a couple of applications where our executable is fired off as a result of unmanaged processing - primarily when processing image data that's been collected and checkpointed by some native code. We've found that GetEntryAssembly
is null
in this instance, whereas the following method works fine.
Now one way that you could add this in would be to add a reference to System.Windows.Forms
into your project and then call it from there - however, there's a way that you can do it without needing to go anywhere near WinForms just by adding a few lines of code. Here it is - in all its glory.
public static class Utility
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer,
int length);
private static string startupPath;
private static HandleRef NullHandleRef = new HandleRef();
public static string StartupPath()
{
if (startupPath == null)
{
StringBuilder buffer = new StringBuilder(260);
GetModuleFileName(NullHandleRef, buffer, buffer.Capacity);
startupPath = Path.GetDirectoryName(buffer.ToString());
}
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, startupPath).Demand();
return startupPath;
}
}
As you can see, the code merely wraps up a call to GetModuleFileName
, it's that simple.
Note - since posting this, one of my fellow WPF Disciples handed over the following code which should work as well:
startupPath = (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()).Location