The issues is due to File.Create(fileLocation)
, which returns a FileStream and keeps the file open. When the StreamWriter attempted to open this, it was already open and caused the error.
To correct the problem, removed the following IF statement:
if (!File.Exists(fileLocation))
{
File.Create(fileLocation);
}
And updated the USING statement as followed. By adding the TRUE parameter, it allows StreamWriter to append to the file if it exists, otherwise create it.
using (var streamWriter = new StreamWriter(fileLocation, true))
{
foreach (var csvRecord in csvfile.CSVRecords)
{
streamWriter.WriteLine(csvRecord.Object_Id + "," + csvRecord.DocumentName + "," + csvRecord.BCI_DCN + "," + csvRecord.CreationDate);
}
}