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

问题描述 投票:0回答:1

在我的WPF项目中,我有一些JSON文件被设置为Content / Copy到Output Folder。当作为标准WPF运行时,我按如下方式访问它们,它工作正常。

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

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

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

wpf desktop-bridge
1个回答
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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.