Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Stream CopyTo() without overwriting existing output file

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?

like image 418
user917670 Avatar asked Feb 21 '23 12:02

user917670


2 Answers

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.

like image 130
Oded Avatar answered Apr 28 '23 13:04

Oded


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.

like image 35
CodeCaster Avatar answered Apr 28 '23 14:04

CodeCaster