The File.CreateText
method returns a StreamWriter
object that is holding the file open. This is not closed and then you try to open the file again with the new StreamWriter
call and hence run into the file in use error. To fix this you need to close the first StreamWriter
outFile = File.CreateText(outFileName);
outFile.Close();
outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8);
Overall this seems a bit wasteful. It would be much more efficient to just create the StreamWriter
instance one time
outFile = new StreamWriter(outFile, false, System.Text.Encoding.UTF8);
The File.CreateText
method is seemingly unnecessary here. If the file doesn't exist StreamWriter
will create it