以前使用的File是操作小的文本文件,用的并不常见,FileStream(操作字节),可以操作所有格式的文件,用途较广泛
下面做一个通过文件流给文件加密解密的小软件.
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace 文件加密{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnFile_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "请选择要加密的文件"; //初始路径 ofd.InitialDirectory = @"C:\Users\home\Desktop"; ofd.Filter = "所有文件|*.*"; ofd.ShowDialog(); txtFile.Text = ofd.FileName; } private void btnCode_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "请选择要保存文件的路径"; sfd.InitialDirectory = @"C:\Users\home\Desktop"; sfd.Filter = "所有文件|*.*"; sfd.ShowDialog(); txtCodeFile.Text = sfd.FileName; //调用方法 MakeCode( "加密"); } private void btnUnCode_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "请选择要保存文件的路径"; sfd.InitialDirectory = @"C:\Users\home\Desktop"; sfd.Filter = "所有文件|*.*"; sfd.ShowDialog(); txtCodeFile.Text = sfd.FileName; //调用方法 MakeCode("解密"); } public void MakeCode(string content) { //1 先读取文件 using (FileStream fsRead = new FileStream(txtFile.Text.Trim(), FileMode.OpenOrCreate, FileAccess.Read)) { using (FileStream fsWrite = new FileStream(txtCodeFile.Text.Trim(), FileMode.OpenOrCreate, FileAccess.Write)) { //设置进度条 progressBar1.Maximum = (int)fsRead.Length; byte[] buffer = new byte[1024 * 1024 * 5]; while (true) { int r = fsRead.Read(buffer, 0, buffer.Length); if (r == 0) { break; } byte passWord = 0; if (byte.TryParse(txtPassword.Text.Trim(), out passWord)&& content.Equals("加密")) { for (int i = 0; i < buffer.Length; i++) { buffer[i] += passWord; } } if (byte.TryParse(txtPassword.Text.Trim(), out passWord) && content.Equals("解密")) { for (int i = 0; i < buffer.Length; i++) { buffer[i] -= passWord; } } fsWrite.Write(buffer, 0, r); progressBar1.Value = (int)fsWrite.Length; } } MessageBox.Show("保存成功!"); } } }}
1 将普通视频文件通过此工具加密
2 现在打开文件
3 解密成功后打开文件