Search code examples
vb.netfilefilestreamstreamwriteroverwrite

Completely overwrite text file with StreamWriter


I am trying to add a simple toggle to my program which among other things writes to a file. The file contains nothing besides one line of text which I want to either read "on" or "off".

Private Sub PictureBox2_Click(sender As Object, e As EventArgs) Handles PictureBox2.Click

    Dim fStrm As FileStream = File.Open(muteFile, FileMode.OpenOrCreate)
    Dim strmWrtr As StreamWriter = New StreamWriter(fStrm)
    strmWrtr.Flush()

    If PictureBox2.Tag = "On" Then
        PictureBox2.Image = My.Resources.SoundOff
        PictureBox2.Tag = "Off"
        strmWrtr.Write("off", False)
    Else
        PictureBox2.Image = My.Resources.SoundOn
        PictureBox2.Tag = "On"
        strmWrtr.Write("on", False)
    End If

    strmWrtr.Close()
    fStrm.Close()

End Sub

Everything works, but it behaves differently than I expected it to. Writing "off" to the file works fine, but when I use strmWrtr.Write("on," False) the file contains "onf" as if it just overwrote character by character and left what it didn't overwrite. Furthermore, if I change it from "on" and "off" to "123456789" and "off" I am left with "off456789".

The behavior I would like is to completely overwrite the file.

One solution I thought of is to always delete and recreate the file, but I was hoping there is a cleaner way to accomplish this, perhaps I'm just missing something.


Solution

  • You are specifically using FileMode.OpenOrCreate which means "reuse if exists".
    If you want to overwrite the file each time, use FileMode.Create.

    Better yet, don't bother with explicit streams (you are not using Using like you should anyway), and simply do File.WriteAllText(muteFile, "on").