1

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!

4

2 回答 2

2

FileMode.OpenOrCreate我认为解决方案是简单地FileMode.Create在第一行更改为

来自关于System.IO.FileMode的 MSDN 文章..

FileMode.Create 指定操作系统应该创建一个新文件。如果文件已经存在,它将被覆盖。

FileMode.OpenOrCreate 指定操作系统应该打开一个文件(如果存在);否则,应创建一个新文件。

于 2009-01-09T12:56:51.627 回答
0

如果您在打开时不知道您可能正在截断文件,则可以使用 Stream 上的 SetLength 方法来截断它。
http://msdn.microsoft.com/en-us/library/system.io.stream.setlength.aspx

为此,Stream 必须是可写且可查找的。

于 2009-02-20T08:08:49.460 回答