I am trying to use NVelocity templates in a .Net application: using a template to output results to a file. It all seems to work fine except for the fact that the output is never fully overwritten. If my file is 100 characters long and the template only renders 20 characters, the last 80 characters are never altered!
Code sample:
FileStream fileStream = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write);
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
velocityEngine.MergeTemplate(templateName, Encoding.Default.WebName, velocityContext, streamWriter);
}
So if my template outputs AAAA and the file already contains BBBBBBBB then at the end, the file contains AAAABBBB at the end of the op.
Any clue how I can get it to fully overwrite the file? - e.g. in the above example the final output should be AAAA. Not too sure whether this is just pure stream-related stuff - but I haven't had this problem before with filestreams.
Happy to write a reset method, or just output to a memorystream and overwrite the file, but I would like to get it working like this if possible! **EDIT:'' got it working by calling
fileStream.SetLength(0);
when I open the file. But would appreciate knowing if there was a better way!