Why is my text file incomplete after using StreamWriter object?

Gregory MOUSSAT picture Gregory MOUSSAT · Sep 11, 2013 · Viewed 7.6k times · Source

I wrote a small program which generates big text files. I found using a StreamWriter is much, much faster than other methods I know. But the end of each text file is missing.

I reduced the program to a very simple snippet to spot the problem, but I'm still unable to understand how to solve it.

#$stream = [System.IO.StreamWriter] "test.txt"
# also tested with  $stream = New-Object System.IO.StreamWriter("test.txt")

$i = 1
while($i -le 500) {
    $stream.WriteLine("$i xxxxxx")
    $i++
}
$stream.flush        # flushing don't change anything
$stream.close        # also tested with   $stream.dispose

exit 0

Problem 1:
The end of the file is missing. Depending of line length, the last line is around 495, generaly cut in the middle of the line.

Problem 2:
When the program is finished, the text file is still locked (we can read it, but not delete/rename). We have to exit from PowerShell to gain full access to the file.

Tested on Windows 2003 and Windows 2008 with exact same result.

EDIT
dugas found the problem: I forgotten some parenthesis. Which solve the problem show with my code snippet.
But my original program have the parenthesis. So I mark this question as solved, and will open a new one when I'll found a better snippet for this specific problem.

EDIT 2
Got it. I had a hidden exception. Many thanks !

Answer

dugas picture dugas · Sep 12, 2013

You are missing parenthesis when calling the StreamWriter's methods:

Change:

$stream.close

to

$stream.Close()

You may also want to wrap your StreamWriter in a try/finally and call Dispose on it in the finally:

try
{
 $stream = [System.IO.StreamWriter] "C:\Users\168357\Documents\test2.txt"
 $stream.WriteLine("xxxxxx")
}
finally
{
 if ($stream -ne $NULL)
 {
  $stream.Dispose()
 }
}