I need help with writing the code to save multiple variables to a text file...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JoshPierce
    New Member
    • Feb 2008
    • 2

    I need help with writing the code to save multiple variables to a text file...

    I want to allow users of my program to click File>Save and have a save dialog open and allow them to save all of their input. here is the background of my program.

    I have a program that allows students to calculate their grades as the class progresses. I want them to be able to type in their information and i already have the program written for them to be able to calculate everything via different types of work based on weights for homework tests etc etc.

    I do not know how to write the code to allow variables to be saved to a text file defined by the user.

    I also do not know how to write the code to allow that user to open that file and import all the data back into it.

    If someone could write me sample code, based on saving these three variables i would greatly appreciate it.

    variables hwPtsPoss (homework points possible), hwPtsAtt (homework points attained), and.... hwWeight (homework weight) all of these are defined as variable type double and standardly use digits and decimals only.

    Thank you very much in advance to whomever can help.
  • DrBunchman
    Recognized Expert Contributor
    • Jan 2008
    • 979

    #2
    Hi Josh,

    The following code is a simple way to create a text file and add some text to it. Hopefully you can see how easy it would be to adapt this for your own uses.

    The last bit with the OpenFileDialog is the bit that you can use to select an existing file and append text to it. The AppendAllText method will open the specified file, add the desired text to the end of the file and then close it. You can use the OpenFileDialog to display the contents of a text file in a rich text box or similar as well.

    First you need to import the IO namespace.

    Code:
     Imports System.IO
    Then the code:

    Code:
     
     
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     
    'CREATE A STREAMWRITER OBJECT TO ACT AS A FILE POINTER 
    Dim fp As StreamWriter
    Dim sText As String = ""
     
    Try
     
    'CREATE THE FILE
    fp = File.CreateText("C:\test.txt")
     
    'DEFINE THE TEXT WE ARE GOING TO ENTER
    sText += hwPtsAtt.ToString
    sText += " out of "
    sText += hwPtsPoss.ToString
    sText += " with a weighting of "
    sText += hwWeight.ToString
     
    'WRITE THE TEXT TO THE FILE
    fp.WriteLine(sText)
     
    'CLOSE THE FILE POINTER
    fp.Close()
     
    Catch ex As Exception
    End Try
     
    OpenFileDialog1.ShowDialog()
     
    File.AppendAllText(OpenFileDialog1.FileName, "HELLO WORLD")
     
     
    End Sub
    Have a play around with it and let me know how you get on,

    Dr B

    Comment

    Working...