在Desktop Bridge下运行时无法访问输出目录中的文件

时间:2019-04-22 23:12:18

标签: wpf desktop-bridge

在我的WPF项目中,我有一些JSON文件被设置为“内容/复制到输出文件夹”。当以标准WPF运行时,我可以按以下方式访问它们,效果很好。

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

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

  

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

1 个答案:

答案 0 :(得分:0)

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);
        }
    }
相关问题