C#属性设置(Properties.Settings)无法设置任何值

6

我想修改"MyProject.Properties.Settings.Default.Property"中的值,但是出现了以下错误:

错误代码 CS0200,属性或索引器'Settings.Version'无法分配--它是只读的

我该如何解决这个问题?或者我可以尝试哪些不同的方法?

21.03.2017 编辑 - 我用下面的方法解决了这个问题

Properties.Settings.Default["Version"] = File.GetLastWriteTime(mainDllPath).ToString("ddMMyyyyhhmmss");
Properties.Settings.Default.Save();

1
你为什么要重新分配应用程序配置设置的值?通常这些设置是由你的应用程序用户设置的,而不是程序本身。 - MakePeaceGreatAgain
如果我的回答解决了您的问题,我会感激您将其标记为已接受的答案。如果没有解决,请告诉我,我会尽力提供更多帮助。 - ScottishTapWater
3个回答

7

来自Microsoft

Settings that are application-scoped are read-only, and can only be changed at design time or by altering the .config file in between application sessions. Settings that are user-scoped, however, can be written at run time just as you would change any property value. The new value persists for the duration of the application session. You can persist the changes to the settings between application sessions by calling the Save method.

How To: Write and Persist User Settings at Run Time with C#:

Access the setting and assign it a new value as shown in this example:

Properties.Settings.Default.myColor = Color.AliceBlue;

If you want to persist the changes to the settings between application sessions, call the Save method as shown in this example:

Properties.Settings.Default.Save();

User settings are saved in a file within a subfolder of the user’s local hidden application data folder.

在这里了解更多有关使用C#中设置的信息


我不使用你的方法,因为我之前尝试过微软代码,但不能在运行时进行更改。 - muratoner
设置有两个不同的范围:用户和应用程序。只有具有用户范围的设置才可以在运行时进行编辑。要检查您的设置: 转到“解决方案资源管理器”>展开项目的“属性”节点>双击.settings文件。 在那里,您可以创建具有用户范围的自己的设置,并在运行时进行编辑,如果这是您的意图。 - Marcello

3

看起来你正在尝试从代码中在运行时编辑此只读属性。你不能这样做。

要更改版本,您需要通过解决方案资源管理器访问项目属性,并在其中更改。

在这种特殊情况下,版本号被添加到编译后可执行文件的元数据中,并且需要对主机操作系统可访问,而不实际运行代码。因此,实时更改这个是不切实际的。


0

用户作用域:可修改的 应用程序作用域:只读


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接