如何使用强类型对象写入我自己的 app.config?

发布于 2024-07-25 16:08:20 字数 1997 浏览 3 评论 0原文

下面的代码有两个缺陷,我无法弄清楚它们是错误还是设计使然。 据我所知,应该可以使用 Configuration.Save 并根据 http://www.codeproject.com/KB/cs/SystemConfiguration.aspx 代码应该可以工作。

这些错误显示在下面的源代码中,并在您尝试设置属性或保存配置时出现。

Imports System.Configuration

Public Class ConfigTest
    Inherits ConfigurationSection
<ConfigurationProperty("JunkProperty", IsRequired:=True)> _
Public Property JunkProperty() As String
    Get
        Return CStr(Me("JunkProperty"))
    End Get
    Set(ByVal value As String)
        ' *** Bug 1, exception ConfigurationErrorsException with message "The configuration is read only." thrown on the following line.
        Me("JunkProperty") = value
    End Set
End Property

Public Sub Save()
    Dim ConfigManager As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

    ' The add / remove is according to http://www.codeproject.com/KB/cs/SystemConfiguration.aspx
    ConfigManager.Sections.Remove("ConfigTest")
    ' *** Bug 2, exception InvalidOperationException thrown with message "Cannot add a ConfigurationSection that already belongs to the Configuration."
    ConfigManager.Sections.Add("ConfigTest", Me)
    ConfigManager.Save(ConfigurationSaveMode.Full, True)

End Sub

Public Shared Sub Main()
    Dim AppConfig As ConfigTest = TryCast(ConfigurationManager.GetSection("ConfigTest"), ConfigTest)

    AppConfig.JunkProperty = "Some test data"
    AppConfig.Save()

End Sub

' App.Config should be:
'    <?xml version="1.0" encoding="utf-8" ?>
    '<configuration>
    '  <configSections>
    '    <section name="ConfigTest" type="ConsoleApp.ConfigTest, ConsoleApp" />
    '  </configSections>
    '  <ConfigTest JunkProperty="" />
    '</configuration>

End Class

我想这样做,以便在第一次运行应用程序时,我检查属性,然后告诉用户如果需要设置,则以管理员身份运行,其中 UI 将帮助他们进行设置。 我已经“以管理员身份运行”但没有效果。

The following code has two flaws, I can't figure out if they are bugs or by design. From what I have seen it should be possible to write back to the app.config file using the Configuration.Save and according to http://www.codeproject.com/KB/cs/SystemConfiguration.aspx the code should work.

The bugs are shown in the source below and appear when you try to set the property or save the config back out.

Imports System.Configuration

Public Class ConfigTest
    Inherits ConfigurationSection
<ConfigurationProperty("JunkProperty", IsRequired:=True)> _
Public Property JunkProperty() As String
    Get
        Return CStr(Me("JunkProperty"))
    End Get
    Set(ByVal value As String)
        ' *** Bug 1, exception ConfigurationErrorsException with message "The configuration is read only." thrown on the following line.
        Me("JunkProperty") = value
    End Set
End Property

Public Sub Save()
    Dim ConfigManager As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

    ' The add / remove is according to http://www.codeproject.com/KB/cs/SystemConfiguration.aspx
    ConfigManager.Sections.Remove("ConfigTest")
    ' *** Bug 2, exception InvalidOperationException thrown with message "Cannot add a ConfigurationSection that already belongs to the Configuration."
    ConfigManager.Sections.Add("ConfigTest", Me)
    ConfigManager.Save(ConfigurationSaveMode.Full, True)

End Sub

Public Shared Sub Main()
    Dim AppConfig As ConfigTest = TryCast(ConfigurationManager.GetSection("ConfigTest"), ConfigTest)

    AppConfig.JunkProperty = "Some test data"
    AppConfig.Save()

End Sub

' App.Config should be:
'    <?xml version="1.0" encoding="utf-8" ?>
    '<configuration>
    '  <configSections>
    '    <section name="ConfigTest" type="ConsoleApp.ConfigTest, ConsoleApp" />
    '  </configSections>
    '  <ConfigTest JunkProperty="" />
    '</configuration>

End Class

I'd like to do it this way so that on the first run of the app I check for the properties and then tell the user to run as admin if they need to be set, where the UI would help them with the settings. I've already 'run as admin' to no effect.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

水溶 2024-08-01 16:08:21

也许您不懂葡萄牙语或 C#,但这正是您想要的 http:// www.linhadecodigo.com.br/Artigo.aspx?id=1613

使用来自 asp.net 的 BuildProvider

Maybe you don't know Portuguese or c# but this is you want http://www.linhadecodigo.com.br/Artigo.aspx?id=1613

using BuildProvider from asp.net

随风而去 2024-08-01 16:08:21

加载配置后,默认情况下它是只读的,主要是因为您没有覆盖 IsReadOnly 属性。 尝试覆盖它。

¿有什么东西阻止您使用某个设置吗?

After loading a configuration it is readonly by default, principally because you have not overriden the IsReadOnly property. Try to override it.

¿Is there something that prevents you from using a setting?

饮湿 2024-08-01 16:08:21

看起来设计上是不可能的。 App.config 通常受到保护,因为它与应用程序一起驻留在 Program Files 目录中,因此安装程序必须在安装时进行修改。

真的很遗憾,我希望该应用程序具有管理员可以设置的设置。

Looks like it is not possible by design. App.config is normally protected as it resides along with the app in the Program Files directory so must be amended at installation time by the installer.

Pity really, I'd like the app to have settings that an admin can set.

萌能量女王 2024-08-01 16:08:21

抱歉,如果我不明白你的情况,但是是的,你可以在运行时更改 App.config 。

实际上,您需要更改 YourApp.exe.config,因为一旦编译您的应用程序,App.config 内容就会复制到 YourApp.exe.config 中,并且您的应用程序永远不会回头查看 App.config。

这就是我所做的(C# 代码 - 抱歉,我还没学过 VB.Net)

 public void UpdateAppSettings(string key, string value)
    {

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        foreach (XmlElement item in xmlDoc.DocumentElement)
        {
            foreach (XmlNode node in item.ChildNodes)
            {

                if (node.Name == key)
                {
                    node.Attributes[0].Value = value;
                    break;
                }
            }
        }

        using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile))
        {
            xmlDoc.Save(sw);
        }

Sorry if I didn't understand your case, but yes, you can change App.config at runtime.

Actually, you will need to change YourApp.exe.config, because once your app is compiled, App.config contents are copied into YourApp.exe.config and your application never looks back at App.config.

So here's what I do (C# code - sorry, I still haven't learnt VB.Net)

 public void UpdateAppSettings(string key, string value)
    {

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        foreach (XmlElement item in xmlDoc.DocumentElement)
        {
            foreach (XmlNode node in item.ChildNodes)
            {

                if (node.Name == key)
                {
                    node.Attributes[0].Value = value;
                    break;
                }
            }
        }

        using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile))
        {
            xmlDoc.Save(sw);
        }
岁月蹉跎了容颜 2024-08-01 16:08:20

你的代码实际上没有任何意义。 我采用了您的示例代码并将其变成了一个有效的简单示例。 请注意,这不是最佳实践代码,只是一个帮助您学习配置 API 的示例。

Public Class ConfigTest
    Inherits ConfigurationSection
    <ConfigurationProperty("JunkProperty", IsRequired:=True)> _
    Public Property JunkProperty() As String
        Get
            Return CStr(Me("JunkProperty"))
        End Get
        Set(ByVal value As String)
            ' *** Bug 1, exception ConfigurationErrorsException with message "The configuration is read only." thrown on the following line.
            Me("JunkProperty") = value
        End Set
    End Property

    Public Overrides Function IsReadOnly() As Boolean
        Return False
    End Function



    Public Shared Sub Main()
        Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        Dim AppConfig As ConfigTest = config.GetSection("ConfigTest")

        AppConfig.JunkProperty = "Some test data"
        config.Save()
    End Sub
End Class

此代码将打开配置文件,修改属性 JunkProperty 并将其保留回可执行文件的配置文件。 希望这能让您开始 - 看起来您需要更多地了解配置 API。

我使用 API 为大型企业应用程序创建配置部分,其中包含 1000 行自定义分层配置(不过我的配置是只读的)。 一旦您学会了配置 API,它就会非常强大。 我进一步了解其功能的一种方法是使用 Reflector 来查看 .NET 框架如何在内部使用 API。

Your code doesn't really make any sense. I took your example code and turned it into a simple example that works. Please note this is not best practise code, merely an example to aid you on your journey of learning the configuration API.

Public Class ConfigTest
    Inherits ConfigurationSection
    <ConfigurationProperty("JunkProperty", IsRequired:=True)> _
    Public Property JunkProperty() As String
        Get
            Return CStr(Me("JunkProperty"))
        End Get
        Set(ByVal value As String)
            ' *** Bug 1, exception ConfigurationErrorsException with message "The configuration is read only." thrown on the following line.
            Me("JunkProperty") = value
        End Set
    End Property

    Public Overrides Function IsReadOnly() As Boolean
        Return False
    End Function



    Public Shared Sub Main()
        Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        Dim AppConfig As ConfigTest = config.GetSection("ConfigTest")

        AppConfig.JunkProperty = "Some test data"
        config.Save()
    End Sub
End Class

This code will open the config file, modify the attribute JunkProperty and persist it back it the executable's configuration file. Hopefully this will get you started- it looks like you need to read about the configuration API a bit more.

I've used the API to create configuration sections for large scale enterprise apps, with several 1000 of lines of custom hierarchical config (my config was readonly though). The configuration API is very powerful once you've learnt it. One way I found out more about its capabilities was to use Reflector to see how the .NET framework uses the API internally.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文