Hello there, I've been busy nowadays with file manipulation and I've so far I've encountered a small problem in appending the contents of a file to another file. This is what I did:

string filename = @"C:\Temp.txt";
string body = null;
StreamReader sr = File.OpenText(files); 
body = sr.ReadToEnd();
StreamWriter sw = File.Create(filename);
sw.WriteLine(body);

sr = File.OpenText(files2);
body = sr.ReadToEnd();
File.AppendAllText(filename, body);

sw.Close();

It seems that I can't append the content of files2 to my Temp.txt file after placing the contents of files. Please help. Thanks.

Dani AI

Generated

Quick diagnosis and a safe pattern to follow.

Your code works once you stop holding the destination file open while trying to append to it. As hinted, writing the second file’s content with the same writer (or closing the writer before calling File.AppendAllText) fixes the problem. Common pitfalls: using File.Create (which truncates/creates) and leaving that StreamWriter open, or reusing StreamReader variables without disposing them — either can lock the file or leak handles.

For small files, open the target once in append mode and write each source into it. This avoids multiple opens and ensures the file is closed cleanly:

var sources = new[] { "source1.txt", "source2.txt" };
using (var writer = new StreamWriter(destPath, append: true))
{
    foreach (var src in sources)
    {
        using (var reader = new StreamReader(src))
        {
            writer.Write(reader.ReadToEnd());
            writer.WriteLine(); // optional separator between files
        }
    }
}

For very large files, stream bytes rather than loading whole files into memory:

using (var outFs = new FileStream(destPath, FileMode.Append, FileAccess.Write))
{
    foreach (var src in sources)
    {
        using (var inFs = new FileStream(src, FileMode.Open, FileAccess.Read))
        {
            inFs.CopyTo(outFs);
        }
        var sep = System.Text.Encoding.UTF8.GetBytes(Environment.NewLine);
        outFs.Write(sep, 0, sep.Length);
    }
}

Troubleshooting tips: use using blocks to guarantee disposal; watch encoding (UTF-8 vs default); catch IOException for sharing/lock issues; avoid File.Create if you meant to append; and prefer File.AppendAllText/File.AppendAllLines only for small files because they allocate memory for the whole contents. This should make appending reliable and scalable for multiple files.

Recommended Answers

All 3 Replies

Why not just do the writeline of body you read from the second file?

Thanks for the reply Ma'am. Will it still append?

Hello again, it seems it is working. I will try it with more than two text files. Thank you.

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.