How to Read and Write Data to a Text Document

I was wondering if anyone could tell me how to read and write lines of text from a text document, such as one that's opened with Notepad.

I'm making a very simple movie database program and I want to be able to take the text typed in a Text Box, write it to a new line in a text document (and save it), and also read text from a line in the document, and then convert that to a string to be used in the program.

Thanks.



Answer this question

How to Read and Write Data to a Text Document

  • Kynaeus

    Hi. The following should work alright for the task you're describing.

            Dim filePath As String = "c:\test.txt"
            Dim textFile As New IO.FileStream(filePath, IO.FileMode.OpenOrCreate)
            Dim textRead As New IO.StreamReader(textFile)
            Dim contents As String = textRead.ReadToEnd
            textRead.Close()

            ' do something with the contents here

            Dim textWrite As New IO.StreamWriter(filePath)
            textWrite.Write(contents)
            textWrite.Close()

    Let me suggest an alternate approach. I would simply create a dataset, add whatever structures describe the data you're needing to save, and then just save the dataset to xml. When you open the program you can just read the xml back in and I'm pretty sure you'll find this is easier to work with. That would look something like:

            Dim filePath As String = "c:\test.xml"
            Dim testDataSet As New Dataset1

            ' optionally open an existing file
            If IO.File.Exists(filePath) Then
                testDataSet.ReadXml(filePath)
            End If

            ' do something with the data here

            ' write the data back out when you're finished.
            testDataSet.WriteXml(filePath)

     

    I hope this gets you moving the right direction.

    Christopher

     



  • How to Read and Write Data to a Text Document