views:

469

answers:

2

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!

+1  A: 

I think the solution is to change the FileMode.OpenOrCreate to simply FileMode.Create in the first line

From the MSDN Article on System.IO.FileMode..

FileMode.Create Specifies that the operating system should create a new file. If the file already exists, it will be overwritten.

FileMode.OpenOrCreate Specifies that the operating system should open a file if it exists; otherwise, a new file should be created.

Andrew
A: 

If you don't know, at open time, that you may be truncating the file, you can use the SetLength method on the Stream to truncate it.
http://msdn.microsoft.com/en-us/library/system.io.stream.setlength.aspx

For this to work, the Stream must be writable and seekable.

Cheeso