在我的WPF项目中,我有一些JSON文件被设置为Content / Copy到Output Folder。当作为标准WPF运行时,我按如下方式访问它们,它工作正常。
foreach (var config in Directory.GetFiles("HostConfigs", "*.json"))
但是当我使用打包项目在桌面桥下运行应用程序时,它会抛出以下异常
System.IO.DirectoryNotFoundException:'无法找到路径的一部分'C:\ WINDOWS \ SysWOW64 \ HostConfigs'。'
Desktop Bridge项目不会自动将当前目录设置为项目的输出文件夹...它们使用Windows的默认目录。
要在您的项目中修复此问题,请在主要启动点(App.xaml.cs
)处添加以下内容...
public partial class App : Application
{
public App()
{
SetCurrentDirectory();
}
/// <summary>
/// Sets the current directory to the app's output directory. This is needed for Desktop Bridge, which
/// defaults to the Windows directory.
/// </summary>
private void SetCurrentDirectory()
{
// Gets the location of the EXE, including the EXE name
var exePath = typeof(App).Assembly.Location;
var outputDir = Path.GetDirectoryName(exePath);
Directory.SetCurrentDirectory(outputDir);
}
}