Completely overwrite a file with Velocity / NVelocity

I am trying to use NVelocity templates in a .Net application: using a template to output the results to a file. Everything seems to work fine, except for the fact that the output is never completely overwritten. If my file is 100 characters long and the template only displays 20 characters, the last 80 characters will never be changed!

Sample code:

        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 hints how I can get it to completely overwrite the file? - eg. in the above example, the final output should be AAAA. Not too sure if this is just thread related stuff - but I haven't had this issue before with threads.

Happy to write a reset method or just output to memystream and overwrite the file, but I would like to get it to work like this if possible! ** EDIT: '' got the job by calling

 fileStream.SetLength(0);

      

when i open the file. But it would be helpful to know if there is a better way!

+1


source to share


2 answers


I think the solution is to change FileMode.OpenOrCreate

to just FileMode.Create

the first line

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



FileMode.Create Indicates 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 the file if it exists; otherwise, a new file must be created.

+2


source


If you don't know at open time that you can trim 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 searchable.

0


source







All Articles