SIGN UP MEMBER LOGIN:    
ARTICLE

Split and Merge files in C#

Posted by Vamshi Krishna Articles | C# Language April 01, 2011
This example shows how to split and merge files in C# .Net.
Reader Level:
Download Files:
 


This example shows how to split files and merge files in C# .Net.

FileStream Open File [C#]:

By using the FileStream class, files can be opened for reading or writing; this article is about how to load and save files using FileStream in C#. The FileStream class has "FileMode" and "FileAccess" enumerations as parameters.

[C#] Open existing file for reading:

FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read);

Prepare Windows form:

Split.gif

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Splitfiles
{
    public partial class Form1 : Form
    {
        public FileStream fs;
        string mergeFolder;
        public Form1()
        {
            InitializeComponent();
        }
        List<string> Packets = new List<string>();

        //Merge file is stored in drive
        string SaveFileFolder = @"c:\";

//Code Under Brows button:                  

        private void brows_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog1.ShowDialog();
                txtBrowsFile.Text = openFileDialog1.FileName;              

                fs = new FileStream(txtBrowsFile.Text, FileMode.Open, FileAccess.Read);
                int FileLength = (int)fs.Length / 1024;
                string name = Path.GetFileName(txtBrowsFile.Text);
            }
            catch (Exception ex)
            {
                lblSendingResult.Text = "EXCEPTION:" + ex;
            }
        }
//Code Under Split button:

        private void btnSplit_Click(object sender, EventArgs e)
        {
            SplitFile(txtBrowsFile.Text, Convert.ToInt32(5));
            listBox1.Items.Add(Packets[0].ToString());
            listBox1.Items.Add(Packets[1].ToString());
            listBox1.Items.Add(Packets[2].ToString());
            listBox1.Items.Add(Packets[3].ToString());
            listBox1.Items.Add(Packets[4].ToString());          
        }

        public bool SplitFile(string SourceFile, int nNoofFiles)
        {
            bool Split = false;
            try
            {
                FileStream fs = new FileStream(SourceFile, FileMode.Open, FileAccess.Read);
                int SizeofEachFile = (int)Math.Ceiling((double)fs.Length / nNoofFiles);

                for (int i = 0; i < nNoofFiles; i++)
                {
                    string baseFileName = Path.GetFileNameWithoutExtension(SourceFile);
                    string Extension = Path.GetExtension(SourceFile);

                    FileStream outputFile = new FileStream(Path.GetDirectoryName(SourceFile) + "\\" + baseFileName + "." +
                        i.ToString().PadLeft(5, Convert.ToChar("0")) + Extension + ".tmp", FileMode.Create, FileAccess.Write);

                    mergeFolder = Path.GetDirectoryName(SourceFile);

                    int bytesRead = 0;
                    byte[] buffer = new byte[SizeofEachFile];

                    if ((bytesRead = fs.Read(buffer, 0, SizeofEachFile)) > 0)
                    {
                        outputFile.Write(buffer, 0, bytesRead);
                        //outp.Write(buffer, 0, BytesRead);

                        string packet = baseFileName + "." + i.ToString().PadLeft(3, Convert.ToChar("0")) + Extension.ToString();
                        Packets.Add(packet);
                    }

                    outputFile.Close();

                }
                fs.Close();
            }
            catch (Exception Ex)
            {
                throw new ArgumentException(Ex.Message);
            }

            return Split;
        }

//Code Under Merge button:
//Files have been merged and saved at location C:\\"

        private void btnMergeFile_Click(object sender, EventArgs e)
        {
            MergeFile(mergeFolder);
        }

        public bool MergeFile(string inputfoldername1)
        {
            bool Output = false;

            try
            {
                string[] tmpfiles = Directory.GetFiles(inputfoldername1, "*.tmp");

                FileStream outPutFile = null;
                string PrevFileName = "";

                foreach (string tempFile in tmpfiles)
                {
                    string fileName = Path.GetFileNameWithoutExtension(tempFile);
                    string baseFileName = fileName.Substring(0, fileName.IndexOf(Convert.ToChar(".")));
                    string extension = Path.GetExtension(fileName);

                    if (!PrevFileName.Equals(baseFileName))
                    {
                        if (outPutFile != null)
                        {
                            outPutFile.Flush();
                            outPutFile.Close();
                        }
                        outPutFile = new FileStream(SaveFileFolder + "\\" + baseFileName + extension, FileMode.OpenOrCreate, FileAccess.Write);

                    }

                    int bytesRead = 0;
                    byte[] buffer = new byte[1024];
                    FileStream inputTempFile = new FileStream(tempFile, FileMode.OpenOrCreate, FileAccess.Read);

                    while ((bytesRead = inputTempFile.Read(buffer, 0, 1024)) > 0)
                        outPutFile.Write(buffer, 0, bytesRead);

                    inputTempFile.Close();
                    File.Delete(tempFile);
                    PrevFileName = baseFileName;

                }

                outPutFile.Close();
                lblSendingResult.Text = "Files have been merged and saved at location C:\\";
            }
            catch
            {

            }

            return Output;

        }
    }
}
 

erver'>
Login to add your contents and source code to this article
share this article :
post comment
 

nice one but here problem is that split option works fine, but when i click merge option it is not taking the .000 file when i previous spitted..

Posted by Ejas Shaik Feb 21, 2012

I rate you 5

Posted by faizal ahamd Dec 30, 2011

In button code: SplitFile(txtBrowsFile.Text, Convert.ToInt32(5)); instead you give SplitFile(txtBrowsFile.Text, Convert.ToInt32(500));

Posted by Vamshi Krishna Nov 12, 2011

Hi, Very interesting article. Lets suppose you wont to split the file in 500 parts, how would you modify the code? Thanks for helping.

Posted by Felice Massaro Nov 11, 2011

BIG THANKS, I will use this many times !

Posted by Boris Dob Apr 28, 2011
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor