Split a text file into several based on output file size.

T

TJ

I am very new to C# (this is my first real project), therefore please be
patient if my question is considered being to newbie.



I am modifying a program which takes a text file, does some formatting then
outputs the resulting file. What I am trying to do is have the program make
as many files as is needed, each limited to a given file size (in this case
240KB).



As way of example say I have a text file which is 723KB (I get this by using
Fileinfo.length) named Test.txt. Program runs and does it's formatting and
is ready to save the output file. In this case the program should make the
following files:

Test1.txt (240KB)

Test2.txt (240KB)

Test3.txt (204KB)

Test4.txt (3KB)



Can anyone offer either in simple steps a solution or place to start to
perform this operation. Remember I am not trying to determine the size of
an existing file, but trying to output X number of files based on a given
maximum file size for each.



Thank you,

tj
 
D

Dan Bass

To clarify what you're trying to do:
- you want your application to take in the name of a text file
- another parameter you want is the max size of each "chunk"
- then you want your application to return how many "chunks" the text file
will be split into?
- presumably you want your application to perform this split?

The easiest (perhaps not the most efficient) way to do this would be to open
the file and read out the contents into a StreamReader.

int maxChunkSizeKB = 240; // size in kilobytes
int maxChunkSizeB = maxChunkSizeKB * 1024; // convert to bytes (==
characters)
string textFileName = @"C:\test.text";
StreamReader rdr = File.OpenText ( textFileName );


then take this file and place it into a string buffer

string fileBuffer = rdr.ReadToEnd();
rdr.Close();


now cut up the file into sizeable files

int fileCounter = 0;
while ( fileBuffer.Length > 0 )
{
//
// get this chunk contents

fileCounter++;
string fileChunkBuffer = "";
if ( fileBuffer.Length > maxChunkSizeB )
{
fileChunkBuffer = fileBuffer.SubString( 0, maxChunkSizeB );
fileBuffer = fileBuffer.SubString ( maxChunkSizeB );
}
else
{
fileChunkBuffer = fileBuffer;
fileBuffer = "";
}

//
// write this chunk file

string chunkFileName = textFileName + fileCounter.ToString();
StreamWriter wtr = File.CreateText ( chunkFileName );
wtr.Write( fileChunkBuffer );
wtr.Close();
}


The number of files that were created is therefore equal to the value of
fileCounter.
I didn't compile this so you may need to tweak it.

Hope that helps.

Daniel.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top