异步读写文件
紧接上一章,从官网例子中学习简单的文件读写
public static string readData;
public static async Task SimpleWriteAsync(string text)
{
string filePath = "simple.txt";
await File.WriteAllTextAsync(filePath, text);
}
public static async Task SimpleReadAsync()
{
string filePath = "simple.txt";
readData = await File.ReadAllTextAsync(filePath);
}
JSON序列化和反序列化
需要用到 System.Text.Json
JsonSerializer Class
导入 Json 包
用命令行
dotnet add package System.Text.Json --version 7.0.0-preview.5.22301.12
引用
using System.Text.Json;
using System.Text.Json.Serialization;
写个玩家类
class Player
{
// 必须是 public 并且有 getter 才能被 JsonSerializer 序列化
public string name { get; set; }
public int age { get; set; }
public int money { get; }
public void log(string s)
{
Console.WriteLine(s + " " + this.name + " " + this.age + " " + this.money);
}
}
static async Task Main()
{
// 序列化 把玩家转化为 JSON
Player p = new Player();
p.name = "小明";
p.age = 24;
p.log("p:");
string data = JsonSerializer.Serialize(p);
// 异步写入文件
await SimpleWriteAsync(data);
Console.WriteLine("写入数据");
// 异步读取文件
await SimpleReadAsync();
Console.WriteLine("读出数据" + readData);
// 反序列化 将字符串转化为玩家对象
Player p2 = JsonSerializer.Deserialize<Player>(readData);
p2.log("p2:");
}
打印结果
p: 小明 24 0
写入数据
读出数据{"name":"\u5C0F\u660E","age":24,"money":0}
p2: 小明 24 0