文件分割小程序
最近发现一个问题 ,就是平常解决过的一些问题过几天又不记得了,所以想把平常这些小东西保存起来,所以想写博了
这是第一个,文件分割器,觉得和其他人的差不多,但是自己写的,所以还是保存起来吧,注释都写了,将就着看吧。如果谁 看到了,想用拿去用,想改拿去改.
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class FileSplite : System.Web.UI.Page
{
/// <summary>
/// 文件分割成的块数 整个程序为方便看,没有提取一些函数,这样一步步的下去反而更加直观
/// </summary>
private int PartCount = 3;
string OldFilePath = "D://bb.jpg";//the File is want to Split
string PartFile1 = "D://part1.part";//分割成的第一部分文件
string PartFile2 = "D://part2.part";
string FileMergePath = "D://a.jpg";//合并后的文件
protected void Page_Load(object sender, EventArgs e)
{
if (File.Exists(PartFile1))
{
FileMerge(PartFile1, PartFile2);
}
else
{
FileSplit();
}
}
private void FileSplit()
{
int FileLength = Convert.ToInt32(new FileInfo(OldFilePath).Length);//The File's Length
BinaryReader BR = new BinaryReader(File.Open(OldFilePath, FileMode.Open));//define a binaryread to read byte from source file
byte[] Bytes = BR.ReadBytes(FileLength / 2);//这里就是程序的瓶颈,所以只能分割int类型最大值的文件,这里有一个好处,防止声明不必要的byte长度而浪费空间
WriteFile(Bytes, PartFile1);
Bytes = BR.ReadBytes(FileLength - FileLength / 2);
WriteFile(Bytes, PartFile2);
}
/// <summary>
/// 文件合并
/// </summary>
/// <param name="FilePart1">第一块的文件物理路径</param>
/// <param name="FilePart2"></param>
private void FileMerge(string FilePart1,string FilePart2)
{
//将块1文件的数据读出来
int FileLength = Convert.ToInt32(new FileInfo(FilePart1).Length);
BinaryReader BR = new BinaryReader(File.Open(FilePart1, FileMode.Open));
byte[] Bytes1 = BR.ReadBytes(FileLength);
//将块2文件的数据读出来
FileLength = Convert.ToInt32(new FileInfo(FilePart2).Length);
BR = new BinaryReader(File.Open(FilePart2, FileMode.Open));
byte[] Bytes2 = BR.ReadBytes(FileLength);
//声明一个写文件流,将块1块2分别以b的单位写到文件里
FileStream FS = new FileStream(FileMergePath, FileMode.Create);
foreach (byte b in Bytes1)
{
FS.WriteByte(b);
}
foreach (byte b in Bytes2)
{
FS.WriteByte(b);
}
FS.Close();
}
/// <summary>
/// 将指定的byte[]数据存放到指定的文件块
/// </summary>
/// <param name="Byte"></param>
/// <param name="FileName"></param>
private void WriteFile(byte[] Byte,string FileName)
{
FileStream FS = new FileStream(FileName, FileMode.Create);
FS.Write(Byte, 0, Byte.Length);
FS.Close();
}
}