如何在C#中为帐户中创建持久字典?

问题描述 投票:0回答:1
我不知道该怎么做,所以我所有的代码基本上都是来自AI的,但是我需要制作一个可以让几个人登录的程序。我想通过一部词典来完成此操作,该字典在关闭程序后无法清除自己。我不知道我在做什么错或如何正确执行此操作,并使其也通过其他形式起作用。

public class PersistentDictionary { private readonly string _filePath; public PersistentDictionary(string filePath) { _filePath = filePath; } public void Save(Dictionary<string, string> createdAccounts) { var json = JsonSerializer.Serialize(createdAccounts); File.WriteAllText(_filePath, json); } public Dictionary<string, string> Load() { if (!File.Exists(_filePath)) { return new Dictionary<string, string>(); } var json = File.ReadAllText(_filePath); return JsonSerializer.Deserialize<Dictionary<string, string>>(json); } } public void submitbtn_Click(object sender, EventArgs e) { string userName = userNametxt.Text; string password = passwordtxt.Text; string reType = retypetxt.Text; var filePath = "persistentDictionary.json"; var persistentDictionary = new PersistentDictionary(filePath); var createdAccounts = new Dictionary<string, string>(); persistentDictionary.Save(createdAccounts); //Load dictionary from file var loadedDictionary = persistentDictionary.Load(); //Modify entries if (password == reType & password == "/^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\\D*\\d)(?=[^!#%]*[!#%])[A-Za-z0-9!#%]{8,32}$/") createdAccounts.Add(userName, password); persistentDictionary.Save(createdAccounts); userNametxt.Clear(); passwordtxt.Clear(); retypetxt.Clear(); }

	
well,您加载之前的任何现有文件。此代码
c# json forms dictionary .net-core
1个回答
1
投票
var createdAccounts = new Dictionary<string, string>(); persistentDictionary.Save(createdAccounts);

创建新的词典并将其写入碟片。但是,您应该做的是首先加载现有文件,然后执行实际逻辑,一旦完成后,将其保存回文件。

毕竟,这应该做到:
var filePath = "persistentDictionary.json";
var persistentDictionary = new PersistentDictionary(filePath);

//Load dictionary from file
var loadedDictionary = persistentDictionary.Load();

//Modify entries
if (password == reType & password == "/^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\\D*\\d)(?=[^!#%]*[!#%])[A-Za-z0-9!#%]{8,32}$/")
    createdAccounts.Add(userName, password);
    persistentDictionary.Save(createdAccounts);

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.