我需要实现一个新的会员申请,但不能使用数据库。我计划创建一个类来定义每个成员,其中包括姓名、部门等字段。我希望将这些成员的列表保存到文件中(不是纯文本)。所以我的问题是如何将类对象保存到文件中?
谢谢!:)
谢谢!:)
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
class SecureJsonSerializer<T>
where T : class
{
private readonly string filePath;
private readonly ICryptoTransform encryptor;
private readonly ICryptoTransform decryptor;
private const string Password = "some password";
private static readonly byte[] passwordBytes = Encoding.ASCII.GetBytes(Password);
public SecureJsonSerializer(string filePath)
{
this.filePath = filePath;
var rmCrypto = GetAlgorithm();
this.encryptor = rmCrypto.CreateEncryptor();
this.decryptor = rmCrypto.CreateDecryptor();
}
private static RijndaelManaged GetAlgorithm()
{
var algorithm = new RijndaelManaged();
int bytesForKey = algorithm.KeySize / 8;
int bytesForIV = algorithm.BlockSize / 8;
algorithm.Key = key.GetBytes(bytesForKey);
algorithm.IV = key.GetBytes(bytesForIV);
return algorithm;
}
public void Save(T obj)
{
using (var writer = new StreamWriter(new CryptoStream(File.Create(this.filePath), this.encryptor, CryptoStreamMode.Write)))
{
writer.Write(JsonConvert.SerializeObject(obj));
}
}
public T Load()
{
using (var reader = new StreamReader(new CryptoStream(File.OpenRead(this.filePath), this.decryptor, CryptoStreamMode.Read)))
{
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
}
}
}
// my original object
class SavedObject
{
public string Data{get;set}
}
// needed to add a field for last edit
class SavedObject2
{
public DateTime LastEdit{get;set;}
public SavedObject2(SavedObject so){}
}
// need a small restructure so we can now have multiple datas
// 'data' is now obsolete
class SavedObject3
{
public List<string> DataList{get;set;}
public SavedObject3(SavedObject2 so){}
}
首先,您可以使用此工具将类序列化为JSON:Json Net
其次,从您的偏好中找到任何加密工具,有很多选择,这是一个例子:Encode to 64
之后,您可以保存您的文件:
System.File.WriteAllText(@"C:\file.dat","encripted string");