c#实现保存测试结果,下次开启软件,数据不会清零
时间: 2024-05-05 11:21:51 浏览: 15
要实现保存测试结果,下次开启软件,数据不会清零,可以使用本地持久化存储来保存数据。在C#中,可以使用文件、数据库或者XML等方式进行本地持久化存储。
如果你想使用文件进行本地持久化存储,可以使用StreamWriter和StreamReader类来写入和读取数据,具体实现可以参考以下代码:
```csharp
using System.IO;
// 写入数据
StreamWriter sw = new StreamWriter("test.txt");
sw.WriteLine("测试数据1");
sw.WriteLine("测试数据2");
sw.Close();
// 读取数据
StreamReader sr = new StreamReader("test.txt");
string line;
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
sr.Close();
```
如果你想使用数据库进行本地持久化存储,可以使用ADO.NET来连接数据库,并使用SqlCommand来执行SQL语句,具体实现可以参考以下代码:
```csharp
using System.Data.SqlClient;
// 连接数据库
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=TestDB;Integrated Security=True");
conn.Open();
// 创建表
SqlCommand cmd = new SqlCommand("CREATE TABLE TestTable (ID int, Name varchar(50))", conn);
cmd.ExecuteNonQuery();
// 插入数据
cmd = new SqlCommand("INSERT INTO TestTable (ID, Name) VALUES (1, '测试数据1')", conn);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("INSERT INTO TestTable (ID, Name) VALUES (2, '测试数据2')", conn);
cmd.ExecuteNonQuery();
// 查询数据
cmd = new SqlCommand("SELECT * FROM TestTable", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
Console.WriteLine(reader["ID"] + "\t" + reader["Name"]);
}
reader.Close();
// 关闭连接
conn.Close();
```
如果你想使用XML进行本地持久化存储,可以使用XmlDocument类来创建和操作XML文件,具体实现可以参考以下代码:
```csharp
using System.Xml;
// 创建XML文件
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Test");
doc.AppendChild(root);
XmlElement element1 = doc.CreateElement("Data");
element1.InnerText = "测试数据1";
root.AppendChild(element1);
XmlElement element2 = doc.CreateElement("Data");
element2.InnerText = "测试数据2";
root.AppendChild(element2);
doc.Save("test.xml");
// 读取XML文件
doc.Load("test.xml");
XmlNodeList nodes = doc.SelectNodes("/Test/Data");
foreach (XmlNode node in nodes) {
Console.WriteLine(node.InnerText);
}
```
以上三种方式均可以实现本地持久化存储,你可以根据自己的需求选择合适的方式进行实现。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)