Search code examples
vb.netvisual-studio-2013streamwritermy.settings

Writing My.Settings to Text File


OK, so I am having some trouble with writing to a text file, retrieving values from My.Settings. The code is below. The problem is that when I check the text file, it only has the first line (which is just a simple string in the code).

Dim settingsfile As String = Directory.GetCurrentDirectory & "\RapidSend_Settings.txt"
Dim objWriter As New System.IO.StreamWriter(settingsfile, False)
objWriter.WriteLine("This is the introductory line")
For Each strEmail As String In My.Settings.User_Emails 'Specialized.StringCollection
    objWriter.WriteLine("Email " & strEmail)
Next
For Each strHostName As String In My.Settings.User_HostName ' Specialized.StringCollection
    objWriter.WriteLine("Host " & strHostName)
Next
objWriter.WriteLine("End Of File")
objWriter.Close()

This is what the text file looks like after the code:

 This is the introductory line
 End Of File

My question is does anyone know what the problem is, or is there another way to do this. BTW, all the My.Settings are Specialized.StringCollection, so they contain lots of strings.


Solution

  • Since you are no longer using Settings the way it is intended, you are better off creating your own container and managing it yourself:

    • Add a module to your app if there isnt one
    • Add Friend settingsList As New List(Of String) to it

    This will create a global collection of strings you can add your data to. It can be Public or Friend. There are other ways to do this, but this is simplest. Create one for the hosts too.

    Adding to them is simple:

    settingsList.Add(some_STRING_variable)
    

    Then to save in the App shutdown:

    ' get file name to hold the data
    Dim file As String
    file = System.IO.Path.Combine(Environment.GetFolderPath( _
           Environment.SpecialFolder.ApplicationData),  "myproduct", "settings.txt")
    ' result will be Users\Appdata.... where data is supposed to go
    
    ' open a stream
    Using fs As New IO.StreamWriter(file, IO.FileMode.CreateNew)
        Dim n As Integer = 1
        ' loop thru List contents
        For Each s As String In settingsList
            ' ToDo: edit format to fit your needs
            fs.WriteLine(String.Format("{0} = {1}", n.ToString, s))
            n += 1
        Next
    
    End Using         ' close and properly dispose of stream