You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何将Guid列表存储到本地文件并从文件中读取加载

是否可以将Guid列表存储到文件中,也可以从文件中加载该列表?

当然可以实现,下面是两种常用的无额外依赖的实现方案:


方案1:JSON序列化(推荐,代码最简洁)

用.NET内置的System.Text.Json即可完成,无需引入第三方库,序列化后的内容也方便跨程序调用。

保存Guid列表到文件代码:

using System.IO;
using System.Text.Json;

// 你的原有业务逻辑生成targetFaceIds
List<Guid> targetFaceIds = new List<Guid>();
foreach (var imageFileName in targetImageFileNames)
{
    List<DetectedFace> detectedFaces = await DetectFaceRecognize(client, _imagePath + imageFileName, recognitionModel);
    targetFaceIds.Add(detectedFaces[0].FaceId.Value);
}

// 序列化列表后写入本地文件
string jsonContent = JsonSerializer.Serialize(targetFaceIds);
// 可自行替换为你想要的存储路径
await File.WriteAllTextAsync(@"D:\your_path\faceIds.json", jsonContent);
// 同步写入写法:File.WriteAllText(@"D:\your_path\faceIds.json", jsonContent);

从文件加载Guid列表代码:

// 读取文件内容并反序列化为Guid列表
string readJson = await File.ReadAllTextAsync(@"D:\your_path\faceIds.json");
List<Guid> loadedFaceIds = JsonSerializer.Deserialize<List<Guid>>(readJson);
// 同步读取写法:string readJson = File.ReadAllText(@"D:\your_path\faceIds.json");

方案2:纯文本存储(每行一个Guid,方便手动查看编辑)

如果需要手动修改文件内容,可以选择将每个Guid单独存一行。

保存代码:

File.WriteAllLines(@"D:\your_path\faceIds.txt", targetFaceIds.Select(g => g.ToString()));

加载代码:

List<Guid> loadedFaceIds = File.ReadAllLines(@"D:\your_path\faceIds.txt")
    .Select(line => line.Trim())
    // 过滤空行和非法格式的Guid,避免报错
    .Where(line => !string.IsNullOrWhiteSpace(line) && Guid.TryParse(line, out _))
    .Select(Guid.Parse)
    .ToList();

内容的提问来源于stack exchange,提问作者jonasPamm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 21:03:00