A C# snippet demonstrating how to merge 2 files (of any type) into a single file. Need a reference to the System.IO Namespace
Merge 2 files (of any type)
/// <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)
{
try
{
//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
if(streamAppend.CanWrite)
//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;
}
}
srps.software 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 meeting, networking, learning, and sharing knowledge.