Merge 2 files (of any type)


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

About the Author

I have been a professional programmer for a bit over 15 years now (more than that if you could school time and such), focusing mainly on Microsoft technologies for the past 7 years (Mainly C#, it's such a beautiful language).

I am a die hard programmer, I live, eat, sleep & breath code and cannot ever see myself doing anything but this.

/// <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;
} 0 Newbie Poster


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.