I would like to have a merge files in C#. Thx
Merge file C#
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
I would like to have a merge files in C#. Thx
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Charles Henington54 reputationPosted Nov 29, 2024, 9:45 PM EST
static void MergeFiles(string[] inputFiles, string outputFile)
{
using Stream mergeStream = File.Create(outputFile);
foreach (string filename in inputFiles)
{
byte[] fileData = File.ReadAllBytes(filename);
mergeStream.Write(fileData);
}
}
Sangeetha SRank #212 · 11.4K reputationPosted Dec 3, 2024, 12:20 AM EST
To merge files in C#, you can read the contents of each file and write them into a new file.
static void Main(string[] args) { // Specify the input files and the output file string[] inputFiles = { "file1.txt", "file2.txt", "file3.txt" }; // List of files to merge string outputFile = "mergedFile.txt"; // Output file try { using (StreamWriter writer = new StreamWriter(outputFile)) { foreach (string file in inputFiles) { if (File.Exists(file)) { string content = File.ReadAllText(file); writer.WriteLine(content); } else { Console.WriteLine($"File not found: {file}"); } } } Console.WriteLine("Files merged successfully!"); } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } }