Search code examples
vb.netstringbuilder

StringBuilder in .net not writing entire file


I'm trying to write a text file. Here's my main,slightly clipped for clarity:

Private Sub WriteProperty(FilePath As String)
    Try
        SB = New StringBuilder
        WriteConfig()
        'a bunch of methods similar to WriteConfig here...
        Dim File As New System.IO.StreamWriter(FilePath)
        File.WriteLine(SB.ToString())
    Catch ex As Exception
        Dim X As Integer = 5 'cheesy way to add a breakpoint
    End Try
End Sub

And here is one of about a dozen subs that add text to the file:

Private Sub WriteConfig()
    Dim TempSB As New StringBuilder
    TempSB.AppendLine("[CONFIG]")
    TempSB.AppendLine("[END_CONFIG]")
    TempSB.AppendLine("")
    SB.Append(TempSB)
End Sub

There are about a dozen methods that add things like this, most of them add about 2k of text instead of the couple of lines in this example. When I examine SB in the debugger the total result is a little over 15k long. But when I open the file, it's 12k, and the end is all missing - it cuts off in the middle of one of the strings. There is no exception raised.

I know SB has problems with lots of little appends, which is why I used the TempSB's in the subs, but it has the exact same problem, and if I add them directly to SB instead the only difference is the "break" occurs a few characters earlier.

Can anyone offer a suggestion as to what might be happening?


Solution

  • StreamWriter uses an internal buffer. You need to Close() your StreamWriter to force it to write the remaining buffered data to the file. Better yet, wrap it in a Using statement. That will call its Dispose(), which in turn calls its Close().

    Using File As New System.IO.StreamWriter(FilePath)
        File.WriteLine(SB.ToString())
    End Using
    

    There's a convenience method that will do this for you in a single line:

    System.IO.File.WriteAllText(FilePath, SB.ToString())