将值设置为空/空自动 [英] Set value to empty/null automatically

查看:139
本文介绍了将值设置为空/空自动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我在App.Config中有以下代码,如何在运行后关闭程序时将其中的值设置为空。 FIY,该程序将被发布和部署。因此,用户只能更改App.Config中的值,而不能更改程序代码。



Hi i have the following codes in App.Config, how can i set the value in it to empty every time i close the program after i have run it. FIY, this program will be published and deployed. Therefore users can only change the value in App.Config and not the program codes.

<add key="EndDate" value=""/>  





用户可以来App.Config并在每次运行程序时更改EndDate,但在关闭它之后,EndDate中的值将自动设置为空。



我试过这个但没有工作:





Users may come to App.Config and change the EndDate every time they run the program but after they close it, the value in EndDate will set to empty automatically.

I tried this but didnt work:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(StartDate);
config.AppSettings.Settings.Add(StartDate, "");
config.AppSettings.Settings.Remove(EndDate);
config.AppSettings.Settings.Add(EndDate, "");
config.Save(ConfigurationSaveMode.Modified);

推荐答案

不好主意。 这不是app.config的设计目的。只有用户才能修改文件(在构建后实际取名:youApplicationName.exe.config)。这个想法是:你默认将一些数据放到app.config中。在构建时,会创建文件youApplicationName.exe.config,并可以随应用程序一起部署。 (通常,即使没有此文件,您的应用程序也应该正常工作。)



用户可以拥有此文件并将其用作起点并编辑以更改某些文件配置细节。应用程序不应该修改它。



如果由于某种原因,你真的想要一些文件,其中一些选项可以通过应用程序修改(无论在什么阶段运行时),您可以使用设置文件。我更喜欢由 Data Contract 构建的一些自定义XML文件,它将直接序列化/反序列化一些代表某些选项/配置的数据类。此文件应写入所有用户的每个用户帐户定义的称为特殊文件夹的位置之一。详情请见我过去的回答:

如何查找我的程序目录 [ ^ ]。



参见: http://msdn.microsoft.com/en-us/library/ms733127.aspx [ ^ ]。



-SA
Bad idea. This is not what "app.config" is designed for. Only the user is supposed to modify the file (which actually takes the name after the build: "youApplicationName.exe.config"). The idea is: you put some data you need to have by default to app.config. On build the file "youApplicationName.exe.config" is created and can be deployed with the application. (Normally, your application should work correctly even if this file is absent.)

The user can have this file and use it as a starting point and edit to change some configuration detail. The application is not supposed to modify it.

If, by some reason, you really want some file with some options modifiable by the application (not matter in what phase of the runtime), you can use a setting file. I would prefer some custom XML file built by Data Contract which will directly serialize/deserialize some data classes representing some options/configuration. This file should be written to one of the locations known as "special folders" defined per user account of for "all users". For detail, please see my past answer:
How to find my programs directory[^].

See also: http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

—SA


查看以下链接

C# - app config不会改变 [ ^ ]


这篇关于将值设置为空/空自动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆