How do I use the Stream CopyTo method without overwriting the existing output file?
public void MergeAndDeleteFiles(string outputFile, IEnumerable<string> inputFiles)
{
using (var output = File.OpenWrite(outputFile))
{
foreach (var inputFile in inputFiles)
{
using (var input = File.OpenRead(inputFile))
{
input.CopyTo(output);
}
}
}
}
The above method overwrites the outputFile for some reason? DO i need to set the position of the output file before using the CopyTo method?
Instead of OpenWrite
use Open
and pass in FileMode.Append
:
using (var output = File.Open(outputFile, FileMode.Append))
This will append the output to the end of the file.
If you want to append data, then use something like this:
using (var output = new FileStream(outputFile, FileMode.Append, FileAccess.Write, FileShare.Write))
{
Or
using (var output = File.Open(outputFile, FileMode.Append))
{
as suggested by Oded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With