Good afternoon,

Can someone help to to understand how to write a student's name and final grade to a sequential file. I am doing this in Visual Basics. I see the syntax for write and read, but is not understanding how to use it in coding.

The answer depends on whether you are replacing what's in the file (or even if there is already a file) or adding to an already existing file. The easiest methods involve reading or writing all of the lines at once. For example, to read all lines of a text file into a string array you can do

Dim lines() As String = System.IO.File.ReadAllLines(filename)

To write them back out just do

System.IO.File.WriteAllLines(filename,stringarray)

If the file doesn't already exist it will be created. To read and process a text file one line at a time you can do

Dim sr As New StreamReader(filename)

Do Until sr.EndOfStream
    Debug.WriteLine(sr.ReadLine)
Loop

sr.Close()

and to write a file you can do

Dim sw As New StreamWriter(filename, True)
sw.WriteLine(string)
sw.WriteLine(string)
sw.Close()

If the second parameter is True then the lines are appended to the file. If False, the lines replace existing data.

Reverend,

I tried your codes and the error list states that "StreamReader is not declared". I am totally confused about this part of my assignment

Reverend Jim,

My file did not exist, so i took the snippets that you gave to create the file. What i am trying to do is to write a student's name and final grade into a new file. But there are errors. Here is what I did so far:

Dim sw As New StreamWriter("C:\StudentMarks.txt", True)
        sw.WriteLine(Of String)()
        sw.WriteLine(Of String)()
        System.IO.File.Open("c:\StudentMarks.txt")
        System.IO.File.WriteAllLines(lblFinal.Text)
        System.IO.File.WriteAllLines(txtStudentName.Text)
        sw.Close()

i did use Imports System.IO in line 2 just before the classname

All you need is

Dim sw As New System.IO.StreamWriter("C:\StudentMarks.txt", True)
sw.WriteLine(txtStudentName.Text & "," & lblFinal.Text)
sw.Close()

but you shouldn't be writing to C:\ under Windows 7 or you will run into UAC issues.

Thanks a lot for your help, the writing to file took!! Yipeeeee!

God Blessings in your life man!

This question has already been answered. Start a new discussion instead.