我想编写一个C#类,可以依次进行对象序列化、压缩和加密。我需要生成的文件:
- 尽可能地快速创建
- 占用尽可能小的空间
- 尽可能不可读
private void SaveObject(string path, object obj)
{
using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
string password = "123";
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
RijndaelManaged RMCrypto = new RijndaelManaged();
using (CryptoStream cryptoStream = new CryptoStream(fileStream, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write))
using (var gZipStream = new GZipStream(cryptoStream, CompressionMode.Compress))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(gZipStream, obj);
}
}
}
private void LoadObject(string path, out object obj)
{
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
string password = "123";
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
RijndaelManaged RMCrypto = new RijndaelManaged();
using (CryptoStream cryptoStream = new CryptoStream(fileStream, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read))
using (var gZipStream = new GZipStream(cryptoStream, CompressionMode.Decompress))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
obj = binaryFormatter.Deserialize(gZipStream);
}
}
}
我是一名业余程序员,对序列化、流和加密知识了解甚少。我甚至很惊讶这段代码能够正常运行。我的问题是:这段代码是否遵循最佳编程实践,能否在不浪费时间或资源的情况下达到足够的目标?
注意:这是一个通用的方法,我将在我的程序中使用它来存储本地数据。