C#文件分割

来源:互联网 发布:股票走势软件 编辑:程序博客网 时间:2024/06/05 11:38

http://www.oschina.net/code/snippet_222150_8303

 

[代码] 文件分割(适合小文件,小于等于64MB)

01using System;
02using System.IO;
03string filetosplit=@"C:\temp\data.bin";
04string targetpath=@"D:\store";
05FileStream fsr = new FileStream(filetosplit, FileMode.Open, FileAccess.Read);
06long FileLength=fsr.Length;
07byte[] btArr = new byte[FileLength];
08fsr.Read(btArr, 0, (int)FileLength);
09fsr.Close();
10int splitcount=3;
11long PartLength=FileLength/splitcount+FileLength%splitcount;
12int nCount=(int)Math.Ceiling((double)FileLength/PartLength);
13string strFileName=Path.GetFileName(filetosplit);
14long byteCount=0;
15for(int i=1;i<=nCount;i++,byteCount=(i<nCount?byteCount+PartLength:FileLength-PartLength))
16{
17    FileStream fsw = new FileStream(targetpath + Path.DirectorySeparatorChar+ strFileName +i, FileMode.Create, FileAccess.Write);
18    fsw.Write(btArr, (int)byteCount, (int)(i<nCount?PartLength:FileLength-byteCount));
19    fsw.Flush();
20    fsw.Close();
21}

[代码] 文件分割(适合大文件,大于64MB)

view source
print?
01using System;
02using System.IO
03string filetosplit=@"C:\temp\data.bin";
04string targetpath=@"D:\store";
05FileStream fsr = new FileStream(filetosplit, FileMode.Open, FileAccess.Read);
06long FileLength=fsr.Length;
07byte[] btArr = new byte[FileLength];
08fsr.Read(btArr, 0, (int)FileLength);
09fsr.Close();
10int splitcount=3;
11long PartLength=FileLength/splitcount+FileLength%splitcount;
12int nCount=(int)Math.Ceiling((double)FileLength/PartLength);
13string strFileName=Path.GetFileName(filetosplit);
14long byteCount=0;
15for(int i=1;i<=nCount;i++,byteCount=(i<nCount?byteCount+PartLength:FileLength-PartLength))
16{
17    FileStream fsw = new FileStream(targetpath + Path.DirectorySeparatorChar+ strFileName +i, FileMode.Create, FileAccess.Write);
18    long bc=byteCount;
19    long PartCount=i<nCount?PartLength:FileLength-bc;
20    int PartBufferCount=(int)(PartCount<int.MaxValue/32?PartCount:int.MaxValue/32);
21    int nc=(int)Math.Ceiling((double)PartCount/PartBufferCount);
22    for(int j=1;j<=nc;j++,bc=(j<nCount?bc+PartBufferCount:PartCount-PartBufferCount))
23        fsw.Write(btArr, (int)bc, (int)(j<nc?PartBufferCount:PartCount-bc));
24    fsw.Flush();
25    fsw.Close();
26}
27fsr.Close();