WPF工作目录

awi*_*nsk 7 wpf

我有一个WPF应用程序通过Windows Installer安装在客户端计算机上.此应用程序还注册了文件扩展名(.xyz),因此当用户双击文件时,它会打开我的WPF应用程序并显示该文件(如Microsoft Word).此程序还有大量未标记为其使用的资源或内容文件的文件(用户手册,零件图纸等).

当用户双击.xyz文件并打开WPF应用程序时,问题就出现了.该应用程序现在具有.xyz文件所在目录的工作目录.现在程序找不到它需要的任何文件(用户手册,零件图等).

处理此类问题的最佳方法是什么?我可以设置工作目录(Environment.CurrentDirectory),但是当用户保存或打开.xyz文件时,我的打开文件对话框会更改工作目录.我可以使用包uri作为零件图,但我使用Process.Start作为用户手册,因为它们是PDF.我试着搜索,但无法想出任何问题.

bre*_*dan 5

您应该能够通过查找可执行文件的目录或使用反射来查找assemly的目录来访问您的安装目录:

通过查找可执行文件,您可以添加对Windows.Forms的引用以使其工作(当然不理想):

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

string appPath = Path.GetDirectoryName(Application.ExecutablePath);
Run Code Online (Sandbox Code Playgroud)

使用反射:

using System.IO;
using System.Reflection;

string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).CodeBase);
Run Code Online (Sandbox Code Playgroud)

要么

string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
Run Code Online (Sandbox Code Playgroud)

您可以只缓存应用程序的路径上载,因为它不会更改.


Mar*_*ant 5

程序集的位置和应用程序的工作目录之间存在差异。有时这些可能是相同的,但情况一定不是这样。要更改工作目录,您可以从中执行应用程序cmd.exe,或者仅在工作目录中创建具有不同目录的快捷方式Start in

您可以像这样获取应用程序的工作目录:

System.IO.Path.GetFullPath(".")
Run Code Online (Sandbox Code Playgroud)

注意: -Directory.始终是当前工作目录,我们只是获取它的绝对路径。有时您可能不需要绝对路径。例如,如果您想读取工作目录中的文件:

new StreamReader("./file-in-the-working-directory.txt");
Run Code Online (Sandbox Code Playgroud)

甚至:

new StreamReader("file-in-the-working-directory.txt");
Run Code Online (Sandbox Code Playgroud)