亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

試圖打開他人的應用程序配置文件

試圖打開他人的應用程序配置文件

C#
慕桂英546537 2021-11-07 20:34:45
我正在使用 C# 和 .NET Framework 4.7 開發 WinForm 應用程序。使用這個應用程序,我試圖從另一個應用程序加載配置文件:string applicationName = Environment.GetCommandLineArgs()[1];if (!string.IsNullOrWhiteSpace(applicationName)){    if (!applicationName.EndsWith(".exe"))        applicationName += ".exe";    string exePath =         Path.Combine(Environment.CurrentDirectory, applicationName);    try    {        // Get the configuration file. The file name has        // this format appname.exe.config.        System.Configuration.Configuration config =          ConfigurationManager.OpenExeConfiguration(exePath);但是ConfigurationManager.OpenExeConfiguration(exePath)拋出異常:An error occurred while loading the configuration file: The 'exePath' parameter is not valid.Parameter name: exePath配置文件AnotherApp.exe.config 存在于文件夾中Environment.CurrentDirectory。我也嘗試將其更改為Path.Combine(@"D:\", applicationName);,但出現相同的異常。如果我在這里添加exe.config, 而不是.exe, 在名稱的末尾applicationName += ".exe";,它似乎打開了一些東西:config.FilePathis D:\AnotherApp.exe.config.config。但是config對象是空的。它沒有填充任何屬性。我究竟做錯了什么?
查看完整描述

1 回答

?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

在嘗試打開之前AnotherApp.exe.config,ConfigurationManager.OpenExeConfiguration檢查AnotherApp.exe磁盤上是否存在。這是來源:


// ...

else {

    applicationUri = Path.GetFullPath(exePath);

    if (!FileUtil.FileExists(applicationUri, false))

        throw ExceptionUtil.ParameterInvalid("exePath");


    applicationFilename = applicationUri;

}


// Fallback if we haven't set the app config file path yet.

if (_applicationConfigUri == null) {

    _applicationConfigUri = applicationUri + ConfigExtension;

}

如您所見,exePath最終被傳遞到FileUtils.FileExists,最終檢查是否exePath代表磁盤上的文件。在你的情況,這是AnotherApp.exe,這并沒有存在。該throw ExceptionUtil.ParameterInvalid("exePath");語句是您的錯誤的來源。


在我上面包含的源代碼中,您可以看到_applicationConfigUri設置為AnotherApp.exe.config(它是絕對路徑,但為了簡單起見,我使用了相對路徑)。當您將 設置exePath為 時AnotherApp.exe.config,代碼最終會檢查AnotherApp.exe.config它找到的(它認為這是 exe 本身)是否存在。在此之后,_applicationConfigUri被設置為AnotherApp.exe.config.config它不會不存在,但配置系統不在這種情況下錯誤輸出(而不是返回一個空的配置對象)。

看來解決這個問題可能有兩種選擇:

  1. 包括AnotherApp.exe在旁邊AnotherApp.exe.config。

  2. 使用ConfigurationManager.OpenMappedExeConfiguration,它允許您提供自己ExeConfigurationFileMap的指示配置系統如何定位.config文件。如果您需要這方面的幫助,請告訴我,我將提供一個示例,說明這應該如何工作。


查看完整回答
反對 回復 2021-11-07
  • 1 回答
  • 0 關注
  • 219 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號