利用FileStream对文件进行加密解密,将文件转化成二进制流,对二进制流进行操作,再保存进去,解密的时候,相反过程也一样的.
private void btnChooesFile_Click(object sender, EventArgs e)
{
//选择要加密的文件
OpenFileDialog fs = new OpenFileDialog();
fs.InitialDirectory = @"D:\";
fs.Filter = "(*.rar)|*.rar";
if (fs.ShowDialog()== DialogResult.OK)
{
txtFilename.Text = fs.FileName;
}
}
private void btnDes_Click(object sender, EventArgs e)
{
//加密,对读出来的字节进行每个字节(255-r)再存
string s = txtFilename.Text;
string path = Path.GetDirectoryName(s);
string filename = "222.rar";
string fullname = Path.Combine(path,filename);
using(FileStream fs2=new FileStream(fullname,FileMode.Create))
{
using(FileStream fs=new FileStream(s,FileMode.Open))
{
byte[] bytes=new byte[1024];//缓冲区大小
int readbyte;
while((readbyte=fs.Read(bytes,0,bytes.Length))>0)
{
for (int i = 0; i <= readbyte;i++ )
{
bytes[i] = (byte)(byte.MaxValue- bytes[i]);
}
//ShowMsg("写入了:" + readbyte.ToString() + "字节");
fs2.Write(bytes, 0, readbyte);//写入文件
}
}
//ShowMsg("写入成功");
}
}
void ShowMsg(string s)
{
txtShow.AppendText(s+"\r\n");
}
private void btnChooesDES_Click(object sender, EventArgs e)
{
}
private void btnUDes_Click(object sender, EventArgs e)
{
//加密,对读出来的字节进行每个字节(255-r)再存
string s = txtFilename.Text;
string path = Path.GetDirectoryName(s);
string filename = "333.rar";
string fullname = Path.Combine(path, filename);
using (FileStream fs2 = new FileStream(fullname, FileMode.Create))
{
using (FileStream fs = new FileStream(s, FileMode.Open))
{
byte[] bytes = new byte[1024];//缓冲区大小
int readbyte;
while ((readbyte = fs.Read(bytes, 0, bytes.Length)) > 0)
{
for (int i = 0; i <= readbyte; i++)
{
bytes[i] = (byte)(byte.MaxValue - bytes[i]);
}
ShowMsg("写入了:" + readbyte.ToString() + "字节");
fs2.Write(bytes, 0, readbyte);//写入文件
}
}
//ShowMsg("写入成功")
}
}