Yesterday, my colleague told me that there was a weird issue that existed in our WPF sample code for Dynamic .NET TWAIN. What we wanted to implement was to create two projects, and start one application from another. The problem was, when we started the invoked application independently, it worked well. Whereas when it was invoked from another application, none of the UI resources loaded.
ImageBrush dpTitle.Background = new ImageBrush(new BitmapImage(new Uri(imageDirectory + "title.png", UriKind.RelativeOrAbsolute))); // Loading UI resources
Because of this behavior, I thought the resource path might be wrong. After I investigated the source code, I found that our developer used the Property Environment.CurrentDirectory.
Here is the code:
String imageDirectory = Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.IndexOf("Samples")) + @"Samples\Bin\Images\WpfDemoImages\";
Refering to Microsoft’s remarks “By definition, if this process starts in the root directory of a local or network drive, the value of this property is the drive name followed by a trailing slash (for example, “C:\”). If this process starts in a subdirectory, the value of this property is the drive and subdirectory path, without a trailing slash (for example, “C:\mySubDirectory”)”, using this property seems to be completely correct.
To verify this issue, I decided to check the directory output in the two different cases.
The output directory for running the app independently:
C:\Users\admin\Desktop\HTTP_Directory\Dynamic .NET TWAIN 5.0 Trial\Samples\Bin\Images\WpfDemoImages\
Start the app from another app:
Process.Start(@"C:\Users\admin\Desktop\HTTP_Directory\Dynamic .NET TWAIN 5.0 Trial\Samples\C# Samples\VS 08\WpfControlsDemo\WpfControlsDemo\bin\Debug\WpfControlsDemo.exe");
C:\Users\admin\Desktop\HTTP_Directory\WPF TEst\WPF TEst\bin\Debug
As you can see, the two result are different. The second output directory is the working directory of the caller application. In this situation, the Property Environment.CurrentDirectory cannot return the expected result.
Is there an alternative? As a matter of fact, Microsoft provides another method. Here is what I found:
String strAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location； String imageDirectory = strAssemblyPath.Substring(0, strAssemblyPath.IndexOf("Samples")) + @"Samples\Bin\Images\WpfDemoImages\";
This method returns the location of the loaded executable file. Therefore, we can easily find out the relative path of the resource files. Now, our WPF projects can work perfectly.