欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#文件分割的方法

程序员文章站 2023-11-21 12:15:16
本文实例讲述了c#文件分割的方法。分享给大家供大家参考。具体如下: 1. 小文件分割(适用于小于等于64m的文件): using system; using...

本文实例讲述了c#文件分割的方法。分享给大家供大家参考。具体如下:

1. 小文件分割(适用于小于等于64m的文件):

using system;
using system.io;
string filetosplit=@"c:\temp\data.bin";
string targetpath=@"d:\store";
filestream fsr = new filestream(filetosplit, filemode.open, fileaccess.read);
long filelength=fsr.length;
byte[] btarr = new byte[filelength];
fsr.read(btarr, 0, (int)filelength);
fsr.close();
int splitcount=3;
long partlength=filelength/splitcount+filelength%splitcount;
int ncount=(int)math.ceiling((double)filelength/partlength);
string strfilename=path.getfilename(filetosplit);
long bytecount=0;
for(int i=1;i<=ncount;i++,bytecount=(i<ncount?bytecount+partlength:filelength-partlength))
{
  filestream fsw = new filestream(targetpath + path.directoryseparatorchar+ strfilename +i, filemode.create, fileaccess.write);
  fsw.write(btarr, (int)bytecount, (int)(i<ncount?partlength:filelength-bytecount));
  fsw.flush();
  fsw.close();
}

2. 大文件分割(适用于大于64m的文件)

using system;
using system.io
string filetosplit=@"c:\temp\data.bin";
string targetpath=@"d:\store";
filestream fsr = new filestream(filetosplit, filemode.open, fileaccess.read);
long filelength=fsr.length;
byte[] btarr = new byte[filelength];
fsr.read(btarr, 0, (int)filelength);
fsr.close();
int splitcount=3;
long partlength=filelength/splitcount+filelength%splitcount;
int ncount=(int)math.ceiling((double)filelength/partlength);
string strfilename=path.getfilename(filetosplit);
long bytecount=0;
for(int i=1;i<=ncount;i++,bytecount=(i<ncount?bytecount+partlength:filelength-partlength))
{
  filestream fsw = new filestream(targetpath + path.directoryseparatorchar+ strfilename +i, filemode.create, fileaccess.write);
  long bc=bytecount;
  long partcount=i<ncount?partlength:filelength-bc;
  int partbuffercount=(int)(partcount<int.maxvalue/32?partcount:int.maxvalue/32);
  int nc=(int)math.ceiling((double)partcount/partbuffercount);
  for(int j=1;j<=nc;j++,bc=(j<ncount?bc+partbuffercount:partcount-partbuffercount))
    fsw.write(btarr, (int)bc, (int)(j<nc?partbuffercount:partcount-bc));
  fsw.flush();
  fsw.close();
}
fsr.close();

希望本文所述对大家的c#程序设计有所帮助。