Merge 2 files (of any type)

PsychoCoder 2 Tallied Votes 174 Views Share

A C# snippet demonstrating how to merge 2 files (of any type) into a single file. Need a reference to the System.IO Namespace

/// <summary>
/// method for merging 2 files into a single file
/// </summary>
/// <param name="fileToAppendTo">the file to merge with</param>
/// <param name="fileToAppend">the file to merge</param>
/// <returns></returns>
public bool MergeFiles(string fileToAppendTo, string fileToAppend)
        //open a file stream of the file that will be holding the 2nd file
        //appended to it
        using (var streamAppend = new FileStream(fileToAppendTo, FileMode.Append))
            //open a file stream for the file being appended
            using (var streamOpen = new FileStream(fileToAppend, FileMode.Open))
                //create byte array the size of the 2nd file
                byte[] array = new byte[streamOpen.Length];
                //read the file into the byte array
                streamOpen.Read(array, 0, (int)streamOpen.Length);
                //let's make sure the stream is writable
                    //write the 2nd file to the first file
                    streamAppend.Write(array, 0, (int)streamOpen.Length);
        //if we've made it this file all went well
        return true;
    catch (IOException ex)
        MessageBox.Show(string.Format("Error merging files: {0}", ex.Message), "Merge Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return false;