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,您加载之前的任何现有文件。此代码
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);