在桌面桥下运行时无法访问输出目录中的文件



在我的WPF项目中,我有一些JSON文件被设置为内容/复制到输出文件夹。作为标准 WPF 运行时,我按如下方式访问它们,它工作正常。

foreach (var config in Directory.GetFiles("HostConfigs", "*.json"))

但是当我使用打包项目在桌面桥下运行应用程序时,它会引发以下异常

System.IO.DirectoryNotFoundException:"找不到路径'C:\WINDOWS\SysWOW64\HostConfigs'的一部分。

桌面桥项目不会自动将当前目录设置为项目的输出文件夹...他们改用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);
        }
    }

最新更新