Search code examples
vb.nettext-files

Creating/editing textfile through VB.NET


How do I code the algorithm below in VB.NET?

Procedure logfile()
{
    if "C:\textfile.txt"=exist then
        open the textfile;
    else
        create the textfile;
    end if  
    go to the end of the textfile;
    write new line in the textfile;
    save;
    close;
}

Solution

  • Dim FILE_NAME As String = "C:\textfile.txt"
    Dim i As Integer
    Dim aryText(4) As String
    
    aryText(0) = "Mary WriteLine"
    aryText(1) = "Had"
    aryText(2) = "Another"
    aryText(3) = "Little"
    aryText(4) = "One"
    
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
    
    For i = 0 To 4
        objWriter.WriteLine(aryText(i))
    Next
    
    objWriter.Close()
    MsgBox("Text Appended to the File")
    

    If you set the second parameter to True in the System.IO.StreamWriter's constructor it will append to a file if it already exists, or create a new one if it doesn't.