我希望能够打开文件,读取字节,添加值(我的加密密钥)并将其写入新文件。 所以我的问题是这种方法还可以吗?
const int ENCRYPE_KEY = 12345;
static void Encrypt(string fileName)
{
using (FileStream streamToRead = File.OpenRead(fileName))
{
using (BinaryReader reader = new BinaryReader(streamToRead))
{
using (FileStream streamToWrite = File.Create(@"D:\temp\encrypted.jpg"))
{
using (BinaryWriter writer = new BinaryWriter(streamToWrite))
{
for (int i = 0; i < streamToRead.Length; i++)
{
byte b = reader.ReadByte();
writer.Write((byte)(b + ENCRYPE_KEY));
}
}
}
}
}
}
答案 0 :(得分:2)
而不是箭头反模式我建议使用 Linq 查询(如果文件足够小 - ReadAllBytes
- 以适应内存):
var target = File
.ReadAllBytes(fileName)
.Select(b => (byte)(unchecked(b + ENCRYPE_KEY))) // do not forget to allow overflow
.ToArray();
File.WriteAllBytes(@"D:\temp\encrypted.jpg", target);
答案 1 :(得分:0)
你可以这样做。对我来说似乎更清洁。
byte[] data = File.ReadAllBytes(fileName);
using (FileStream streamToWrite = File.Create(@"D:\temp\encrypted.jpg"))
using (BinaryWriter writer = new BinaryWriter(streamToWrite))
{
for (int i = 0; i < data.Length; i++)
{
writer.Write((byte)(data[i] + ENCRYPE_KEY));
}
}