Why is my text file incomplete after using the StreamWriter object?

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

I reduced the program to a very simple fragment to identify the problem, but I still cannot figure out 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 on the length of the line, the last line is about 495, the total 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 it). We must exit PowerShell to gain full access to the file.

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

EDIT
The problem was found: I forgot the brackets. What solutions show the problem with my code snippet.
But my original program has brackets. Therefore, I mark this issue as being solved and will open a new one when I find the best fragment for this particular problem.

EDIT 2
I get it. I had a hidden exception. Thank you very much!

+6
source share
1 answer

Missing bracket when calling StreamWriter methods:

Edit:

 $stream.close 

to

 $stream.Close() 

You can also wrap your StreamWriter in try / finally and call Dispose on it at the end:

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

Source: https://habr.com/ru/post/953658/


All Articles