如何在文本文件中存储 C# 表单元素属性?
如何将 C# 表单元素属性(例如文本框的位置)存储在文件中,例如文本文件?这样当用户打开表单时,数据就会从文件读取到表单中? 有人告诉我可以使用 XML 配置文件...有人可以告诉我如何在 C# 中做到这一点吗?
How can I store C# form element attributes (such as position of a textbox) in a file eg. text file? So that when the user opens the form, data is read from the file into the form?
I was told I could use an XML config file... can someone please tell me how to do that in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不需要该文件可供人类读取/编辑,则以二进制方式执行此操作会更容易。
创建一个类或结构来保存要保留到文件中的所有数据,使用 [Serialized] 属性对其进行标记,然后使用以下代码。
要从文件中取回类,
使用 XmlSerializer 也可以,但是如果类包含任何集合、列表或其他奇怪的内容,那就有点棘手了
if you don't need the file to be human readable/editable, it's easier to do this in binary.
create a class or struct to hold all the data you want to persist imnto the file, mark it with [Serializable] attribute, and then use following code.
To get the class back from the file,
Doing it with XmlSerializer is fine too, but it gets a bit tricky if the class contains any collections, or lists, or other weirdities
这可能取决于您想要保存给定表单元素属性的详细程度。例如,如果您只想存储大致对应于 3 个表单元素的 X、Y 的 6 个固定值,那么使用 C# 的内置设置效果会很好 - 在 C# 中使用设置 (MSDN)
另一方面,如果您想保留确切的状态对于非固定数量的表单元素,您可以采取更复杂的路线并序列化每个表单元素并以这种方式存储它。这很快就会变得非常复杂。只要看一眼这些,您就会明白我的意思 -
序列化控件到外部文件
WCF 中的序列化
It probably depends on the level of detail you'd like to save about the properties of the given form element. For example, if you only want to store, say, 6 fixed values roughly corresponding to X,Y for 3 form elements, then using C#'s built in settings would work just great -- Using Settings in C# (MSDN)
On the other hand, if you want to preserve the exact state of a non-fixed number of form elements, you could go a much more complex route and serialize each form element and store it that way. That will easily become very complex very quickly. Just glance at these and you'll see what I mean --
Serializing controls to an external file
Serialization in WCF
您不一定需要手动管理文件或手动滚动任何序列化代码。在 WinForms 应用程序中,我使用 Properties.Settings 来存储用户选择的主题等内容。它们非常易于使用,我喜欢它们,因为它们可以强类型化。
这是一篇博客文章关于如何去做。
您还可以通过“设置”存储自定义类型/类。因此,可以想象,您可以使用一个单独的类,其属性反映您想要跟踪的各种表单元素,然后将其存储在用户设置中。如果元素数量不同,您始终可以使用字典或列表。
You don't need to manually manage a file or hand-roll any serialization code necessarily. In WinForms applications I use Properties.Settings for storing things like the user's chosen theme etc. They are very easy to work with and I like them because they can be strongly typed.
Here's a blog post about how to do it.
You can also store custom types/classes via Settings. So conceivably you could a separate class with properties reflecting the various form elements you want to track and then store that in the user settings. If the number of elements varies you could always use a dictionary or list.