将 WinForms (C#) APP 设置迁移到 .config 文件

发布于 2024-08-14 01:22:21 字数 411 浏览 10 评论 0原文

我想将当前使用的设置文件迁移到 appconfig 文件。 目前我正在尝试复制它,但到目前为止我什至无法使用配置管理器将其写入文件。

我需要做的是首先创建文件,然后写入它,最后它已经存在,更新它!看起来很简单,但到目前为止它每次都让我困惑。到目前为止我提到的所有材料都假设它存在。甚至 MS MCTS 参考书也已经为示例制作了一个配置文件。

是否有一种编程方式来创建它,然后写入应用程序的默认 bin 文件夹(假设您有足够的权限)。

这些示例使这看起来非常简单,但是当您查看相关文件上的时间戳时......抓破他的头...帽子掉下来!

我的意思是它们是不同类型的配置文件吗?我知道 web.config 和 app.config,但是人们到底在多大程度上偏离了这个简单的命名模板???

感谢您的回复。 伊布拉尔

I want to migrate the settings file I am currently using to appconfig file.
At the moment I am trying to make a copy of it but so far I cannot even get it to write to the file using the Config' Manager.

What I need to do is first create the file and then write to it and finally of it already exists, update it!. Seems pretty simple but so far its eluding me at every turn. All the materials I have referred to so far ALL ASSUME it exists. Even the MS MCTS reference book has a config file already made for the examples.

Is there a programmatic way of creating it and then writing to the default bin folder of the application assuming you have sufficient privileges.

The examples make this look soo simple but when you look at the timestamps on the file in question ....scratches his head ... hat falls !

I mean are they different types of config files? I know of web.config and app.config but how much do people really deviate from this simple naming template???

Thanks for any replies.
Ibrar

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

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

发布评论

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

评论(5

逆夏时光 2024-08-21 01:22:21

首先,你说 app.config 是一个配置文件。它不是。它是 Visual Studio 中的源文件,VS 在编译期间使用它来创建配置文件。在编译期间,如果 Visual Studio 检测到 app.config,它会将其复制到编译的输出文件夹并将其重命名为(假设程序集的完全限定名称为 NameSpace.your.applicationName),

NameSpace.your.applicationName.exe.config

这是您应该查找的文件,并在您正在编写的任何自定义代码中读取/写入该文件。

正如其他答案提到的,这样做要小心。这并非小事。该文件只是 CLR 用于管理应用程序配置的完整系统的一部分,您很容易弄乱它。

最后,请调查名为 configSource 的配置文件元素。使用此功能,您可以在 app.config 中放置一个元素,“重定向”配置系统以在单独的文件中查找特定的配置部分。您可以通过修改 app.config 中的部分元素来使用它,如下所示:

<MyConfigSectionName configSource="ConfigFolder\MySpecConfigFile.xml" />

或者,将现有的 .Net 配置部分移动到单独的文件中,

<appSettings configSource="ConfigFolder\MyAppSettings.xml" />

然后您可以使用所需的设置创建一个单独的配置文件,然后打开、读取并写入该文件...

文件 MyAppSettings.xml 的内容:

<?xml version="1.0" encoding="utf-8" ?>

<appSettings>
  <add key="limitToSingleInstance" value="true"/>
  <add key="maximumCacheFiles" value="1000"/>
  <add key="maximumThreadCount" value="5"/>
</appSettings>

First of all, You say app.config is a config file. It is not. It is the source file within Visual Studio that is used by VS to create the config file during compilation. During Compilation, if Visual Studio detects an app.config, it copies it to the output folder of the compilatuion and renames it to (assuming the fully qualified name of your assembly is NameSpace.your.applicationName),

NameSpace.your.applicationName.exe.config

That is the file you should be looking for, and reading/writing to in any custom code you are writing.

As other answer mentions, be careful doing this. it is not trivial. this file is only a portion of a complete system that the CLR uses to manage configuration for your application, and you can mess it up easily.

FInally, please investigate the config file element called configSource. Using this, you can place an element in your app.config that "redirects" the configuration system to look in a separate file for a specific config section. You would use it by modifying the section element in the app.config like this:

<MyConfigSectionName configSource="ConfigFolder\MySpecConfigFile.xml" />

or, to move an existing .Net config section to a separate file,

<appSettings configSource="ConfigFolder\MyAppSettings.xml" />

Then you can create a separate config file with the settings you want in it, and open, read, and write to that file...

contents of file MyAppSettings.xml:

<?xml version="1.0" encoding="utf-8" ?>

<appSettings>
  <add key="limitToSingleInstance" value="true"/>
  <add key="maximumCacheFiles" value="1000"/>
  <add key="maximumThreadCount" value="5"/>
</appSettings>
一曲爱恨情仇 2024-08-21 01:22:21

下面是一个示例,说明如何创建自定义配置文件,存储一些配置数据,然后将其与一些 ifexists 语句一起读回以在需要时创建它。希望将其翻译成 C# 不会那么麻烦。

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If System.IO.File.Exists(System.IO.Directory.GetCurrentDirectory() + "\Settings.Config") Then
        FileOpen(1, System.IO.Directory.GetCurrentDirectory() + "\Settings.Config", OpenMode.Random, OpenAccess.ReadWrite)
        FileGet(1, SettingVar1, 1)
        FileGet(1, SettingVar2, 2)
        FileGet(1, SettingVar3, 3)
        'etc
        FileClose(1)
    Else
        FileOpen(1, System.IO.Directory.GetCurrentDirectory() + "\Settings.Config", Openmode.Random, OpenAccess.ReadWrite)
        FilePut(1, "Static Setting to write", 1) 'insert a string
        FilePut(1, 3, 2) 'insert a number
        FilePut(1, New DBMC, 3) 'Any object
        'etc...
        FileClose(1)
    End If
End Sub

可能应该注意的是,.NET 有一个 VB 可以引用的内置设置文件 (My.Settings),它可以执行与此相同的操作,但无需通过代码管理文件的开销。还有用于保存设置变量的注册表(如果您有勇气并承诺在卸载程序时清理注册表),以及许多其他正确的方法来执行此操作。

另外,请注意,许多开发人员不赞成使用随机访问文件,并且由于与大型随机访问文件相关的某些开销成本,它们通常不再被大量使用。然而,为了简单起见,随机访问文件是一种非常容易理解的创建和控制配置文件的方式。

Here is an example of how to create a custom config file, store some configuration data, and then read it back along with some if exists statements to create it if it needs to be. Hopefully it won't be that much trouble to translate it into C#.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If System.IO.File.Exists(System.IO.Directory.GetCurrentDirectory() + "\Settings.Config") Then
        FileOpen(1, System.IO.Directory.GetCurrentDirectory() + "\Settings.Config", OpenMode.Random, OpenAccess.ReadWrite)
        FileGet(1, SettingVar1, 1)
        FileGet(1, SettingVar2, 2)
        FileGet(1, SettingVar3, 3)
        'etc
        FileClose(1)
    Else
        FileOpen(1, System.IO.Directory.GetCurrentDirectory() + "\Settings.Config", Openmode.Random, OpenAccess.ReadWrite)
        FilePut(1, "Static Setting to write", 1) 'insert a string
        FilePut(1, 3, 2) 'insert a number
        FilePut(1, New DBMC, 3) 'Any object
        'etc...
        FileClose(1)
    End If
End Sub

It should probably be noted that .NET has a built in Settings file that VB can reference (My.Settings) that would do the same thing as this but without the overhead of managing the file through code. There is also the registry for saving settings variables (if you're feeling brave and promise to clean up the registry when your program gets uninstalled), and many other correct ways of doing this.

Also, please note that many developers frown on using random access files and they are generally not used much anymore because of certain overhead costs associated with large random access files. However, for the sake of simplicity, a random access file is a very easy-to-understand way of creating and controlling a config file.

樱花落人离去 2024-08-21 01:22:21

成功了。

1)首先将配置文件添加到您的项目中。

2) 命名或重命名为应用程序的名称。

3) 确保它以 .config 结尾

4) 设置配置文件的属性,以便将其复制到输出文件夹。

5) 确保您的项目正确引用项目引用下的配置程序集。

6) 创建配置对象,如下所示:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

-->现在坚持枚举对象上的“None”...稍后针对不同的用户等进行实验。

7) 调试您的项目并运行几次以确保配置对象正确获取配置文件及其文件path 属性正确指向配置文件的位置。所以在运行时这将位于 \bin\debug\ ....
----->还检查 has ffile 属性并确保其也为 true。

8) 在此阶段,配置对象已正确设置并准备就绪。现在添加条目就像使用键值对概念将条目添加到哈希表或字典中一样。

config.AppSettings.Settings.Add("Key", "Value");

9) 添加一些示例测试数据后,最后要做的就是保存配置。

config.Save();

10) 最后,导航到构建输出文件夹并检查文件配置文件是否已更改。

更新:您可能会发现最终出现在输出目录中的 vshost.exe 文件可能会弄乱事情,因为我注意到我的配置对象指向这些 xml 文件之一,而不是我的配置文件。在 VS IDE 之外,这没有问题,因为 vhsost 文件未部署且未使用,但在 IDE 中,很高兴让它全部工作在那里。因此,如果发生这种情况,请关注我下面的帖子。

这就是我或多或少寻找的答案......无论如何,感谢我收到的所有回复。

Got it working.

1) Firstly add a config file to your project.

2) Name or rename it to the name of application -like-for-like.

3) Make sure it ends with .config

4) Set the property on the config file so that it is copied out to the output folder.

5) Make sure your project correctly references the configuration assembly under project references.

6) Create the configuaration object like so for e.g:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

--> Stick with the "None" on the enumeration object for now ... experiment later for different users and etc.

7) Debug your project and run it a few times to make sure the config object is correctly picking up the config file and its file path property correctly points to the location of the config file. So at Run time this is going to be under \bin\debug\ ....
-----> Check for the has ffile property also and make sure its true also.

8) At this stage, the config object is properly set-up and is ready to go. Now add your entries as though you were adding entries into a Hashtable or a Dictionary using the key-value pairs notion.

config.AppSettings.Settings.Add("Key", "Value");

9) Once you have added in some sample test data, last thing to do iss to save the config.

config.Save();

10) Finally, navigate to the build output folder and check to see if the file config file has changed.

UPDATE: You might find that vshost.exe file that ends up in the output directory might mess things up as I noticed my config object was pointed to one of these xml file and not my config file. Outside of the VS IDE this is O.K as the vhsost file is not deployed and not used but in the IDE its nice to get it all working in there. So follow my post below if this happens.

That was the answer I was more or less looking for ... Thanks for all the replies i got anyways.

帅气尐潴 2024-08-21 01:22:21

我自己也对配置文件摸不着头脑。最后,我选择简单地创建我自己的设置类,并根据需要将其作为 XML 序列化(反序列化)到光盘或从光盘中序列化。

序列化您自己的设置文件的注意事项:

  • 更灵活
  • 您必须编写更多代码
  • 类型安全(指按类型而不是字符串 ID 进行设置)

当然还有大量其他注意事项,但第三个是我最喜欢的。

i've scratched my head over the config files myself. In the end i have opted to simply create my own settings class and (de)serialize it as XML to/from disc as needed.

Considerations to serializing your own settings file:

  • More flexible
  • You have to write more code
  • Type safe (refer to setting by type rather than string ID)

Tons of other considerations of course, but the third is my fave.

§对你不离不弃 2024-08-21 01:22:21

尽管这不是答案,而是上一篇文章的后续内容。

private void saveAllMenuItem_Click(object sender, EventArgs e)
    {
        // Set up the config object .... with a default user level.
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        if (isWindowsDriveSet())
        {
            // Save the drive name and write it to a config file.
            config.AppSettings.Settings.Add("Drive", WindowsDrive());
        }
        else
        {
            MessageBox.Show("Please set your windows drive before proceeding!", "Windows Drive Not Set!",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        if (ShowHiddenFilesSetting()) // only true (executes) if the app is showing 'ALL' files.
        {
            config.AppSettings.Settings.Add("FileSettings", FileSettings());
        }
        else // else default is implied.
        {
            config.AppSettings.Settings.Add("FileSettings", FileSettings());            
        }

        // Notify the user that the method has completed successfully.
        toolStripStatusLabel.Text = "Settings saved.";

        // Log to the logger what has just happened here.
        ActionOccured(this, new ActionOccuredEventArgs("0", DateTime.Now.ToString(), "The user has saved his settings."));

        // Finally save to the config.
        config.Save();
    }

上面是我保存应用程序设置的“Save()”方法。虽然我确实设法让它工作......我发现在测试并擦拭每个构建上的区域后,我发现我的应用程序会自动查找“MyFileExplorer.config”,而是查找 vshost.exe.config 文件某种。我不知道为什么它要寻找这个文件?由于 filePath 属性是访问器属性,因此我无法更改它的值。

我将进一步实验看看是否可以让它再次工作!

Even though this is not answer but a follow up from the previous post.

private void saveAllMenuItem_Click(object sender, EventArgs e)
    {
        // Set up the config object .... with a default user level.
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        if (isWindowsDriveSet())
        {
            // Save the drive name and write it to a config file.
            config.AppSettings.Settings.Add("Drive", WindowsDrive());
        }
        else
        {
            MessageBox.Show("Please set your windows drive before proceeding!", "Windows Drive Not Set!",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        if (ShowHiddenFilesSetting()) // only true (executes) if the app is showing 'ALL' files.
        {
            config.AppSettings.Settings.Add("FileSettings", FileSettings());
        }
        else // else default is implied.
        {
            config.AppSettings.Settings.Add("FileSettings", FileSettings());            
        }

        // Notify the user that the method has completed successfully.
        toolStripStatusLabel.Text = "Settings saved.";

        // Log to the logger what has just happened here.
        ActionOccured(this, new ActionOccuredEventArgs("0", DateTime.Now.ToString(), "The user has saved his settings."));

        // Finally save to the config.
        config.Save();
    }

Above is my 'Save()' method that saves application settings. While I did manage to get it working ... i found that after testing and wiping my area down on each build I found that rather my application automatically look for 'MyFileExplorer.config' it instead looks for a vshost.exe.config file of some sort. I have no idea why it is looking for this file? As the filePath property is an accessor property so I can't change it's value.

I will experiment further see if i can get it to work again !

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