Cannot access files in output directory when running under Desktop Bridge

左心房为你撑大大i 提交于 2021-01-29 13:12:27

问题


In my WPF project, I have some JSON files that are set as Content/Copy to Output Folder. When running as standard WPF, I access them as follows and it works fine.

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

But when I run the app under the Desktop Bridge using the packaging project, it throws the following exception

System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\WINDOWS\SysWOW64\HostConfigs'.'


回答1:


Desktop Bridge projects don't automatically set your current directory to your project's output folder... they use Windows' default directory instead.

To fix this across your project, at the main launching point (App.xaml.cs), simply add the following...

    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);
        }
    }


来源:https://stackoverflow.com/questions/55802224/cannot-access-files-in-output-directory-when-running-under-desktop-bridge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!