Click here to Skip to main content
15,905,325 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends

I hope you all doing well,

I have to merge two big file in my winform application. First I used File.WriteAllText(), But it throw memory outof bound exception. So please help me to find a optimized and low memory used code to solve my problem.

Thanks and regards
Posted
Comments
[no name] 27-Feb-14 6:55am    
What file you are trying to merge...??
binoyvijayan 27-Feb-14 7:37am    
its .sql files

Assuming your files are text files, (or you wouldn't be trying WriteAllText) there are a huge number of ways you could do it - but most of the problem is centered on the "Merge" part.
If you have two files on disk, and you want to just create a third file with one following the other, then it's pretty easy:
open the output file, as a stream, and read the input files in chunks, writing each chunk to the output.
C#
private void butMerge_Click(object sender, EventArgs e)
    {
    using (StreamWriter sw = new StreamWriter(@"D:\Temp\Output.txt"))
        {
        AppendFile(sw, @"D:\Temp\MyHugeText1.txt");
        AppendFile(sw, @"D:\Temp\MyHugeText2.txt");
        }
    }

private void AppendFile(StreamWriter sw, string path)
    {
    int blockSize = 1024 * 1024 * 8;
    char[] block = new char[blockSize];
    using (StreamReader sr = new StreamReader(path))
        {
        while (!sr.EndOfStream)
            {
            int chars = sr.Read(block, 0, blockSize);
            sw.Write(block, 0, chars);
            }
        }
    }
 
Share this answer
 
const int chunkSize = 2 * 1024; // 2KB
var inputFiles = new[] { "file1.dat", "file2.dat","file3.dat" };
using (var output = File.Open(outputfile,FileMode.Append))
{
foreach(strng file in inputfiles)
{

using (var input = File.OpenRead(file))
{
var buffer = new byte[chunkSize];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}

}
}

}

I think its have better performance ..
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900