Splites files using C#

Here is the code snippet to Put files under AXE to splits the particular file and then place the output files at target location.

Using System.io;
Using System;

//Method to split files
public void SplitFileBasedOnNumberOfFiles(string inputFile, int noOfFiles,string outPutLocation)

//Open the file in read mode

var fs = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
//read the inputs for how many files user want after splitting
var numberOfFiles = Convert.ToInt32(noOfFiles);
//get the size of each file after splitting
var sizeOfEachFile = (int)Math.Ceiling((double)fs.Length / numberOfFiles);
//start the for loop to go through num of file and split that
var baseFileName = Path.GetFileNameWithoutExtension(inputFile);
var extension = Path.GetExtension(inputFile);

for (var i = 1; i <= numberOfFiles; i++)
//get the base name
//get the extension of the file
//get the out put location with output file name
var outputFile = new FileStream(outPutLocation + “\\” + baseFileName + “_” + i.ToString().PadLeft(5, Convert.ToChar(“0”)) + extension, FileMode.Create, FileAccess.Write);
var bytesRead = 0;
//array of bytes
var buffer = new byte[sizeOfEachFile];
//read the file bytes by bytes and put into output buffer
if ((bytesRead = fs.Read(buffer, 0, sizeOfEachFile))
outputFile.Write(buffer, 0, bytesRead);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s