把配置信息节作为类的属性,构造成一个可序列化的配置类(ConfigSetting);
配置类->二进制序列化->加密->存储成文件(Config.ini)。
读取配置节信息时,可读取文件流->解密->反序列化->配置类。
代码:
配置类:
[Serializable]
public class ConfigSettings{-------}
保存:
序列化到内存流:
//obj is ConfigSettings Class
MemoryStream ms = new MemoryStream();
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(ms, obj );
byte[] SourceByteArray = ms.ToArray();
ms.Close();
加密:
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream msEncrypt = new MemoryStream();
CryptoStream cs = new CryptoStream(msEncrypt, des.CreateEncryptor(key,IV), CryptoStreamMode.Write );
cs.Write(SourceByteArray, 0, SourceByteArray.Length );
cs.FlushFinalBlock();
byte[] byteEncrypt = msEncrypt.ToArray();
cs.Close();
把byteEncrypt写入文件;
读取:
解密:
//source:read file byte[]
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key,IV), CryptoStreamMode.Write );
cs.Write(source, 0, source.Length );
cs.FlushFinalBlock();
cs.Close();
反序列化:
byte[] byteDecrypt = ms.ToArray();
MemoryStream msDecrypt = new MemoryStream( byteDecrypt );
BinaryFormatter serializer = new BinaryFormatter();
Object obj = serializer.Deserialize( msDecrypt );
msDecrypt.Close();
obj 即为配置类(ConfigSetting)转换一下即可使用。
CIO之家 www.ciozj.com 公众号:imciow