Hi;
I have developed a MCQ based learning game. A user has to play the game repeatedly to improve his learning. For each session of game, player gets score. I want to write the score in a single file for every session. e.g. I want to print user name and his score for first game in first line of file and for 2nd game in second line and so on.
At the moment, every time a new session is played it overrides the earlier line. I need some help with the below code.

Dim fs As New FileStream("file1.doc", FileMode.Create, FileAccess.Write)
            Dim s As New StreamWriter(fs)
             s.BaseStream.Seek(0, SeekOrigin.End)
            s.WriteLine(namebox.Text)
            s.WriteLine(scorebox.Text)
            s.Close()

Take a look at "FileMode" in the help index. Your use of FileMode.Create will always create a new file including overwriting the file if it already exists. Instead you want to create a file if it doesnt exist but append to a file if it does exist.

Let me first get this straight.

You want sorta like:
Game 1, User 100
Game 2, User 90

Instead you get this?
Game 2, User 90

Yeah, the second one overwrites the first. 
What I want is if first game score was 
Player1 90

Then second game score should not overwrite it rather appear alongwith it in file when I check file after playing game 2 e.g.

Player1 90
Player1 95 
Player1 96
and so on...

You can add True to append on your code.

Dim s As New StreamWriter(fs,True)

Notice that there is an additional boolean argument?. True if Append/Add.

You can use this new code, which also has a custom error.

Try
            Dim Filewriter As StreamWriter = New StreamWriter("Scores.txt", True)
            Filewriter.WriteLine(namebox.Text & " " & scorebox.Text)
            Filewriter.Close()
        Catch E As Exception
            ' Your own custom error
            MsgBox("Cannot Save")
        End Try

Output to textfile or document file will look like this.
Player1 90
Player1 65

Using

Dim s As New StreamWriter(fs,True)

returns the below error.

Overload resolution failed because no accessible 'New' can be called with these arguments:
'Public Sub New(path As String, append As Boolean)': Value of type 'System.IO.FileStream' cannot be converted to 'String'.
    'Public Sub New(stream As System.IO.Stream, encoding As System.Text.Encoding)': Value of type 'Boolean' cannot be converted to 'System.Text.Encoding'.

Seems to be variable type mismatch (Bolean and string).

I used the following code:

Dim fs As New FileStream("scores.txt", FileMode.Create, FileAccess.Write)
            Dim s As New System.IO.StreamWriter(fs, True)
            Try
                Dim Filewriter As StreamWriter = New StreamWriter("Scores.txt", True)
                Filewriter.WriteLine(namebox.Text & " " & scorebox.Text)
                Filewriter.Close()
            Catch ex As Exception
                MsgBox("Cannot Save")
            End Try

Maybe a Filewriter.Flush() between each WriteLine()? Also, you might not need the Seek(), try taking that out and see if it works.

There is no overload of StreamWriter(stream, append) because the "append" property is specified when you create the stream.

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    Dim fs As New FileStream("scores.txt", FileMode.Create, FileAccess.Write)
    Dim s As New System.IO.StreamWriter(fs)  'This gets the file create/append properties from the New Filestream() line
    Try
      Dim Filewriter As StreamWriter = New StreamWriter("Scores.txt", True)
      Filewriter.WriteLine("abc" & " " & "123")
      Filewriter.Close()
    Catch ex As Exception
      MsgBox("Cannot Save")
    End Try
  End Sub
Dim fs As New FileStream("scores.txt", FileMode.Create, FileAccess.Write)
            Dim s As New System.IO.StreamWriter(fs, True)
            Try
                Dim Filewriter As StreamWriter = New StreamWriter("Scores.txt", True)
                Filewriter.WriteLine(namebox.Text & " " & scorebox.Text)
                Filewriter.Close()
            Catch ex As Exception
                MsgBox("Cannot Save")
            End Try

Ditch the first two lines, and create the .Txt manually first before you go into a more advance phase.

Imports System.IO
        Private Sub Save()
            Try
                Dim Filewriter As StreamWriter = New StreamWriter("Scores.txt", True)
                Filewriter.WriteLine(namebox.Text & " " & scorebox.Text)
                Filewriter.Close()
            Catch ex As Exception
                MsgBox("Cannot Save")
            End Try
        End Sub

After that, you may proceed to checking the file if exists then create if exists.

Edited 7 Years Ago by yorro: n/a

This way it works. Manually creating .txt file first and then appending. Thanks a lot for the solution.

I have one more question to ask, can I use two databases simultaneously using the vb.net. For example, one of my form works for MCQs that show image and answers are text, these are taken from first database. The other form works for given text, answer the correct image option. I want to use both the forms interchangebly using single executable application.
Are there any suggestions?

Edited 7 Years Ago by Learning78: wrong code

This way it works. Manually creating .txt file first and then appending. Thanks a lot for the solution.

The solution pose new problems such as non-existing .txt file or invalid path file, both of which can be solved by checking if the file exist first.

If file not exists then
>create file
>save scores
else
>save scores

As for your question about database, the answer is yes but I haven't tried it myself. My suggestion is to use a manually coded database then use variables to save the connection settings for each databases.

Since you're only writing a small amount of data I would call the static System.IO.File.WriteAllText() and not worry about streams.

lol, i just checked this to try a way to fix my problem that is kinda similar to urs, but i didn't find the solution here, instead i found my own solution which will work on this too probably. instead of "filemode.create" u can go with "filemode.OpenOrCreate" That way the app will check if file exists and just update text along with the old one, or create new file and add the new text. damn i'm good for a mega noob in vb coding.

This article has been dead for over six months. Start a new discussion instead.