gpt4 book ai didi

c# - 是否可以使用c#将结构存储在文本文件中

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:10 26 4
gpt4 key购买 nike

我喜欢将结构存储到文本文件中并检索它。

我创建了一个结构名称学生详细信息包含值

studentid,student name,student avg.i like to store this structure details in Textfile for many students.after that I like reteive from Textfile using student id.我在 windows 表单应用程序中工作。是否有可能C#.

最佳答案

您可以将结构集合存储在 XML 文件中,该文件是结构化文本。
这是一个非常快速的示例,可帮助您入门:

    using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

public class Student {
[XmlElement("id")]
public int id;
[XmlElement("name")]
public string name;
}

[XmlRoot("students")]
public class Students {
[XmlElement("students")]
public List<Student> students = new List<Student>();
}

class Program {
static void Main(string[] args) {
Students s = new Students();
s.students.Add(new Student() { id = 1, name = "John Doe" });
s.students.Add(new Student() { id = 2, name = "Jane Doe" });
XmlSerializer xs = new XmlSerializer(typeof(Students));
using (FileStream fs = new FileStream("students.xml", FileMode.Create, FileAccess.Write)) {
xs.Serialize(fs, s);
}
}
}

你会得到这样的东西:

<?xml version="1.0"?>
<students xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<students>
<id>1</id>
<name>John Doe</name>
</students>
<students>
<id>2</id>
<name>Jane Doe</name>
</students>
</students>

关于c# - 是否可以使用c#将结构存储在文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2988674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com