'Getting error - "Stream was not readable" while reading CSVs and merging them into one

When I run the following code, it fails on the second loop with the error - "Stream was not readable". I don't understand why the stream in the second loop is coming to be closed when it is being created every time in the loop.

string resultCsvContents = "col1,col2,col3\n1,2,3";
using (var streamWriter = new StreamWriter("MergedCsvFile.csv", true))
{
                int fileCount = 0;
                foreach (var outputFilePath in outputFiles)
                {
                    
                    using (var fileStream = mockService.GetFileStream(outputFilePath))
                    {
                        using (var streamReader = new StreamReader(fileStream))
                        {
                            if (fileCount != 0)
                            {
                                var header = streamReader.ReadLine();
                            }

                            streamWriter.Write(streamReader.ReadToEnd());
                            fileCount++;
                        }
                    }
                }
 }

The output of this should be a csv with the following data : col1, col2, col3 1,2,3 1,2,3 1,2,3 Here the mock service is mocked to return string resultCsvContents = "col1,col2,col3\n1,2,3"; mockService.Setup(x => x.GetFileStream(It.IsAny<string>())) .ReturnsAsync(new MemoryStream(Encoding.ASCII.GetBytes(this.resultCsvContents1)));

Is there an issue with the way I am mocking this function ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source