简体   繁体   English

在 Windows 窗体 C# 应用程序的配置文件中设置值

[英]Set a value in a Configuration File in a Windows Forms C# Application

Using Microsoft Visual Studio Community 2019.使用 Microsoft Visual Studio 社区 2019。

How can I set a value (a path) in a Configuration File, so it can be updated and then restart the application with the updated value (without having to recompile the application)?如何在配置文件中设置一个值(路径),以便可以更新它,然后使用更新后的值重新启动应用程序(无需重新编译应用程序)?

This is a legacy project that I don't really know.这是一个我真的不知道的遗留项目。 The most important requirement is to have the capability to change this path without having to recompile the application.最重要的要求是能够更改此路径而无需重新编译应用程序。 This is what I've tried so far:这是我迄今为止尝试过的:

Preliminary step:预备步骤:

To check what kind of project it is.检查它是什么类型的项目。 Based on this question , I check that the .csproj file contains:基于这个问题,我检查.csproj文件是否包含:

<OutputType>WinExe</OutputType>

So, to my understanding the project is a WinForms Application .所以,据我所知,该项目是一个WinForms Application

Also, I've tried to seach for the GUID found in the .csproj file:另外,我尝试搜索在.csproj文件中找到的 GUID:

<ProjectGuid>{B1DD5159-A8E8-4DBE-964F-DB9679F60192}</ProjectGuid>

But the seach for that GUID gives no result, and also is not listed on this two GUID list:但是对那个 GUID 的搜索没有给出结果,也没有列在这两个 GUID 列表中:

Note: The core of the question is based the asumption that this project is a WinForms Application.注意:问题的核心是基于这个项目是一个 WinForms 应用程序的假设。 Please let me know if this the wrong way of finding the type of this project, or even better pointing out the right way of doing it.请让我知道这是否是查找该项目类型的错误方法,或者甚至更好地指出正确的方法。


First step:第一步:

To edit the Configuration File, going to the Solution Explorer, in which I cannot find any .config file, but if I check the files of this project (via Windows Explorer), I found a app.config file.要编辑配置文件,请转到解决方案资源管理器,在其中我找不到任何.config文件,但是如果我检查该项目的文件(通过 Windows 资源管理器),我找到了一个app.config文件。

I update this file outside of Visual Studio (I'll come back to this later), and add a test property.我在 Visual Studio 之外更新了这个文件(稍后我会回来),并添加一个test属性。 This modification is done following the structure found in the file, no external source to do this modification.这个修改是按照文件中的结构完成的,没有外部源来做这个修改。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="LF10Demo.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <userSettings>
        <LF10Demo.Properties.Settings>
            <setting name="AutoStepping" serializeAs="String">
                <value>True</value>
            </setting>
            ...
            <setting name="test" serializeAs="String">
                <value>C:\Temp</value>
            </setting>
        </LF10Demo.Properties.Settings>
    </userSettings>
</configuration>

Then, in the code try to get the value:然后,在代码中尝试获取值:

var appSettings = System.Configuration.ConfigurationManager.AppSettings;
string value1 = System.Configuration.ConfigurationManager.AppSettings["test"];
string value4 = System.Configuration.ConfigurationSettings.AppSettings.Get("test");

None of which bring the value stored in the app.config file, in fact all of then brings null .这些都没有带来存储在app.config文件中的值,实际上所有的都带来了null

Then, update the app.config file following this post configuration file in a Windows Forms C# Application然后,在 Windows 窗体 C# 应用程序中按照此后配置文件更新app.config文件

<?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <add key="test" value="C:\Temp" />
      </appSettings>
    </configuration>

Which didn't work either.这也不起作用。

Second step第二步

Going back to the modification of the app.config , discart this modifications and add a different Configuration File (after all, the app.config is not visible in the Solution Explorer).回到对app.config的修改,去掉这个修改,添加一个不同的配置文件(毕竟app.config在解决方案资源管理器中是不可见的)。 This consist in adding a new configuration file app1.config following this post related with configuration file in a Windows Forms C# Application and also this one Adding and reading from a Config file .这包括在这篇与 Windows Forms C# 应用程序中的配置文件相关的app1.config之后添加一个新的配置文件app1.config这个app1.config and reading from a Config file

So after adding the new configuration file, all my apptemps with System.Configuration.ConfigurationManager.AppSettings brings null .因此,在添加新的配置文件后,我所有带有System.Configuration.ConfigurationManager.AppSettings apptemps 都会带来null

Also, when adding the this new configuration file, if I choose app.config the show me a message saying另外,当添加这个新的配置文件时,如果我选择app.config显示一条消息说

A file with the name 'App.config' already exits...名为“App.config”的文件已经存在...

So after all, the project is (in some way) finding that file.毕竟,该项目正在(以某种方式)找到该文件。

Other related information:其他相关资料:

In the file Settings.Designer.cs if I add the following:如果我在文件Settings.Designer.cs添加以下内容:

[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("C:\\Temp")]
public string test
{
    get {
        return ((string)(this["test"]));
    }
    set {
        this["test"] = value;
    }
}

And then using this line:然后使用这一行:

string value8 = Properties.Settings.Default.test;

Is possible to get the value, but this does not satisfy the requirement that the path can be changed without recompiling the application.是可以获取到值的,但是这不满足不需要重新编译应用程序就可以改变路径的要求。

Other related links:其他相关链接:

This are other links related with adding a configuration file to Visual Studios projects, I've also tried some of this solutions but without obtaining the expected results:这是与向 Visual Studios 项目添加配置文件相关的其他链接,我也尝试了其中的一些解决方案,但没有获得预期的结果:

Look in your bin directory and you should see a file named YourProjectName.exe.config with a type of XML configuration.查看您的 bin 目录,您应该会看到一个名为 YourProjectName.exe.config 的文件,其中包含一种 XML 配置。 Whatever is in your app.config is copied here when you compile the project.编译项目时,app.config 中的任何内容都会复制到此处。 You can change the values in code as follows:您可以按如下方式更改代码中的值:

static void UpdateAppSettings(string key, string value)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;
            settings[key].Value = value;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 C# 在 datagridview Windows 窗体应用程序内的 ComboBox 中设置默认第一个值 - How to Set Default First Value in ComboBox inside the datagridview Windows Forms Application using C# 如何通过 cmake w/o 资源文件为 C# Windows 窗体应用程序设置图标? - How to set an icon for C# Windows Forms application via cmake w/o resource file? 如何在C#Windows窗体项目中设置应用程序关闭模式? - How to Set Application Shutdown Mode in a C# Windows Forms Project? C# - 在Windows窗体应用程序中获取SelectedItem的值 - C# - getting value of SelectedItem in Windows Forms application 有没有办法加密Windows窗体应用程序的配置文件? - Is there a way to encrypt the configuration file of a Windows Forms application? 使用 C# 在 Windows 窗体应用程序中创建 Excel 文件 - Creating Excel file in Windows Forms application using C# 无法使用C#Windows Forms应用程序删除文件 - Cannot Delete File using C# Windows Forms Application C#中应用程序的配置文件 - Configuration file for an application in C# C#Windows应用程序中基于许可证的配置 - License Based Configuration in C# Windows Application c#Windows窗体应用程序窗体问题 - c# Windows form application forms problem
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM