Results 1 to 31 of 31

Thread: [RESOLVED] Reading Data From Lines of .ini File

  1. #1

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Resolved [RESOLVED] Reading Data From Lines of .ini File



    Here's what i've got so far, i've written all of the data that i'm going to put into my config file, however i'm having trouble reading the specific string values that I need from that ini file. The parts of the ini lines I want to get are the values in between the ' ' in value='____'.

    I've tried using streamreader a couple things but i'm having trouble figuring that out. I need to parse each line of the ini file to get that value in between the single quotations, so that I can set the value for my richtextbox background and text color as well as a few other things that i've set up in my notepad including tab spacing and so on. Help would be much appreciated because lots of these different values need to be converted from a string value to integers, and boolean values as well. (4 of them, the rest of them don't have to be changed because they are already string values when my application reads them to determine it's application load settings.

    EDIT: I just noticed in the preview that this is from the version of the app where I had streamwriter write "______ value=" & Something to a file. lol some of the (')s are still in this version, so please excuse that little part. I had them in, but took them out so that I could trim data to get a value easier, but I want to use (')s hopefully when all is said and done.

    For example, just to restate what I want - in the ini file it will read
    [setting name] value='VALUE'

    I want to be able to "get" the string value of "VALUE" within the ini file between the 2 single quotations ' & '.

    Thanks
    Last edited by AceInfinity; May 23rd, 2011 at 12:56 AM.

  2. #2

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    Bumping this thread to get some help on the subject.

  3. #3
    PowerPoster kaliman79912's Avatar
    Join Date
    Jan 2009
    Location
    Ciudad Juarez, Chihuahua. Mexico
    Posts
    2,593

    Re: Reading Data From Lines of .ini File

    there are more elegant or faster ways to do it, but here is an idea:

    If the line always ends with the second '

    after you readln the each line on the file:

    newString = Mid(originalString, InStr(originalString, "'"), Len(originalString)-InStr(originalString, "'")-1)

    note that "'" is a single cuotation between two doubles.

    InStr will find the location of the first appearance of ' on the old string.
    Mid will return the middle part of the old string, begining on the second parameter, with length of the third
    On the third paramenter i am taking the length of the old string - the position of the first ' to eliminate all that part, -1 to take care of the last '
    More important than the will to succeed, is the will to prepare for success.

    Please rate the posts, your comments are the fuel to keep helping people

  4. #4

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    wow, that actually should work in my case. Thanks for putting it in a way that I could understand too, most people just give me the code lol, but I like to learn as well. +1 for you

    I just need to figure out how to get it to read a specific line that I want it to read so that I know what value i'm getting from the line i'm 'trimming' using that code. That's one part that I don't understand, If I did I would have used a similar trimming method like you explained though.

    I want to make sure that the lines i'm trimming, I know what they are so that I can use those values to define the configuration for the right settings.

    ConfigFile.ReadLine("[Word Wrap] value='" & CWordWrap & "'")

    I have something like that, but how to I make it so that it will read the line that begins with [word wrap]? and not another config line (setting)

    CWordWrap will vary, so i'm unsure on how I input that into readline.
    Last edited by AceInfinity; May 23rd, 2011 at 03:37 PM.

  5. #5
    PowerPoster kaliman79912's Avatar
    Join Date
    Jan 2009
    Location
    Ciudad Juarez, Chihuahua. Mexico
    Posts
    2,593

    Re: Reading Data From Lines of .ini File

    If you want to know the field name, like "Editor Text Color" or "Font Type" then use similar code I showed you but look for the "[" and "]" using the InStr function.
    More important than the will to succeed, is the will to prepare for success.

    Please rate the posts, your comments are the fuel to keep helping people

  6. #6

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    Alright, i'll try it

  7. #7
    PowerPoster kaliman79912's Avatar
    Join Date
    Jan 2009
    Location
    Ciudad Juarez, Chihuahua. Mexico
    Posts
    2,593

    Re: Reading Data From Lines of .ini File

    Actually again, if [ is always the first character you only need to search for the second.

    Code:
    newString = Mid(oldString, 2, InStr(oldString, "]")-1)
    Starting at 2 to avoid the [, maybe you would need to subtract 2 to the InStr if you are getting the ] included in the result.
    More important than the will to succeed, is the will to prepare for success.

    Please rate the posts, your comments are the fuel to keep helping people

  8. #8

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    Is there anything wrong with my code?

    If
    Code:
    SettingName = Mid(OriginalString, InStr(OriginalString, "["), Len(OriginalString) - InStr(OriginalString, "]") - 1)
    Is wrong then I could see how that would mess things up.

    vb Code:
    1. Private Sub LoadDefaultConfig()
    2.  
    3.         Dim ConfigFile As New StreamReader("Config.ini")
    4.  
    5.  
    6.         Dim SettingName As String
    7.  
    8.         Dim NewString As String
    9.         Dim OriginalString As String = ConfigFile.ReadLine
    10.  
    11.         Dim CBColor As String
    12.         Dim CTColor As String
    13.         Dim CFormTitleColor As String
    14.         Dim CTMenuColor As String
    15.         Dim CBMenuColor As String
    16.         Dim CFontType As String
    17.         Dim CFontSize As String
    18.         Dim CTabSpacer As String
    19.         Dim CDragDrop As String
    20.         Dim COnTop As String
    21.         Dim CWordWrap As String
    22.  
    23.         SettingName = Mid(OriginalString, InStr(OriginalString, "["), Len(OriginalString) - InStr(OriginalString, "]") - 1)
    24.  
    25.         If SettingName = "Editor Text Color" Then
    26.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    27.             CTColor = NewString
    28.             RichTextBox1.ForeColor = ColorTranslator.FromHtml(CTColor)
    29.         End If
    30.  
    31.         If SettingName = "Editor Background Color" Then
    32.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    33.             CBColor = NewString
    34.             RichTextBox1.BackColor = ColorTranslator.FromHtml(CBColor)
    35.         End If
    36.  
    37.         If SettingName = "Application Title Color" Then
    38.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    39.             CFormTitleColor = NewString
    40.             Label1.ForeColor = ColorTranslator.FromHtml(CFormTitleColor)
    41.             TitleFilename.ForeColor = ColorTranslator.FromHtml(CFormTitleColor)
    42.         End If
    43.  
    44.         If SettingName = "Top Menu Color" Then
    45.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    46.             CTMenuColor = NewString
    47.             MenuStrip1.BackColor = ColorTranslator.FromHtml(CTMenuColor)
    48.         End If
    49.  
    50.         If SettingName = "Bottom Status Menu Color" Then
    51.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    52.             CBMenuColor = NewString
    53.             StatusStrip1.BackColor = ColorTranslator.FromHtml(CBMenuColor)
    54.         End If
    55.  
    56.         If SettingName = "Font Type" Then
    57.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    58.             CFontType = NewString
    59.             RichTextBox1.Font = New System.Drawing.Font(RichTextBox1.Text, CFontType)
    60.         End If
    61.  
    62.         If SettingName = "Font Size" Then
    63.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    64.             CFontSize = NewString
    65.             RichTextBox1.Font = New System.Drawing.Font(RichTextBox1.Text, CFontSize)
    66.         End If
    67.  
    68.         If SettingName = "Tab Spacing Size" Then
    69.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    70.             CTabSpacer = NewString
    71.             FormTabs.NumericUpDown1.Value = CTabSpacer
    72.         End If
    73.  
    74.         If SettingName = "Drag Drop Files" Then
    75.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    76.             CDragDrop = NewString
    77.             RichTextBox1.AllowDrop = CDragDrop
    78.         End If
    79.  
    80.         If SettingName = "Always On Top" Then
    81.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    82.             COnTop = NewString
    83.             Me.TopMost = COnTop
    84.         End If
    85.  
    86.         If SettingName = "Word Wrap" Then
    87.             NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)
    88.             CWordWrap = NewString
    89.             RichTextBox1.WordWrap = CWordWrap
    90.         End If
    91.  
    92.         ConfigFile.Close()
    93.  
    94.  
    95.  
    96.     End Sub

    I tried debugging by returning the value of an example value using a msgbox but it wouldn't return anything after pressing the loaddefault button, so i'm assuming it's not reading any of those values, meaning my line of code for SettingName isn't quite right
    Last edited by AceInfinity; May 23rd, 2011 at 04:27 PM.

  9. #9
    PowerPoster kaliman79912's Avatar
    Join Date
    Jan 2009
    Location
    Ciudad Juarez, Chihuahua. Mexico
    Posts
    2,593

    Re: Reading Data From Lines of .ini File

    Off the top I see that you do not loop through all the lines but only

    Dim OriginalString As String = ConfigFile.ReadLine

    For structure purposes try using CASE SELECT instead of all those IF statements

    If you want to debug its better to put a Break line (F9) and then, once stopped, step through the code with F8 using the watch or local windows to see the values of variables.

    Specially look after the statement

    SettingName = Mid(OriginalString, InStr(OriginalString, "["), Len(OriginalString) - InStr(OriginalString, "]") - 1)

    to see if SettingName is getting the correct trimmings
    Last edited by kaliman79912; May 23rd, 2011 at 04:44 PM.
    More important than the will to succeed, is the will to prepare for success.

    Please rate the posts, your comments are the fuel to keep helping people

  10. #10

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    SettingName isn't returning any string value in the bottom for the data it gives you. It says the String is "Nothing"

    Forgot to loop through the lines though, but i'll revert the if statements to case select.

  11. #11
    PowerPoster kaliman79912's Avatar
    Join Date
    Jan 2009
    Location
    Ciudad Juarez, Chihuahua. Mexico
    Posts
    2,593

    Re: Reading Data From Lines of .ini File

    vb.net Code:
    1. Private Sub LoadDefaultConfig()        
    2. Dim ConfigFile As New StreamReader("Config.ini")          
    3. Dim SettingName As String        
    4. Dim NewString As String        
    5. Dim OriginalString As String
    6.  
    7. Dim CBColor As String        
    8. Dim CTColor As String        
    9. Dim CFormTitleColor As String        
    10. Dim CTMenuColor As String        
    11. Dim CBMenuColor As String        
    12. Dim CFontType As String        
    13. Dim CFontSize As String        
    14. Dim CTabSpacer As String        
    15. Dim CDragDrop As String        
    16. Dim COnTop As String        
    17. Dim CWordWrap As String        
    18.  
    19. SettingName = Mid(OriginalString, InStr(OriginalString, "["), Len(OriginalString) - InStr(OriginalString, "]") - 1)        
    20.  
    21.      Do
    22.           OriginalString = ConfigFile.ReadLine()
    23.           NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)            
    24.  
    25.           Select Case NewString
    26.                Case "Editor Text Color"
    27.                     CTColor = NewString            
    28.                     RichTextBox1.ForeColor = ColorTranslator.FromHtml(CTColor)
    29.                Case "Editor Background Color"
    30.                     CBColor = NewString            RichTextBox1.BackColor = ColorTranslator.FromHtml(CBColor)
    31. .
    32. .
    33. .
    34.           End Select
    35.  
    36.      Loop Until OriginalString Is Nothing
    37.  
    38. .
    39. .
    40. .

    This is just a guideline. Still think there is much more optimization possible but this is the idea. Keep the .readline inside the loop
    More important than the will to succeed, is the will to prepare for success.

    Please rate the posts, your comments are the fuel to keep helping people

  12. #12
    Fanatic Member
    Join Date
    Jul 2009
    Posts
    629

    Re: Reading Data From Lines of .ini File

    Code to parse the following line:
    Code:
    Dim line As String = "[Variable Name] value='test'"
    Get the variable name:
    Code:
    Dim varname As String = line.Remove(0, line.IndexOf("[") + 1)
    varname = varname.Substring(0, varname.IndexOf("]"))
    Get the value (only check using the ' signs):
    Code:
    Dim value1 As String = line.Remove(0, line.IndexOf("'") + 1)
    value1 = value1.Substring(0, value1.IndexOf("'"))
    Get the value (match value= as well):
    Code:
    Dim value2 As String = line.Remove(0, line.IndexOf("value=") + 6).Trim("'").Trim()
    You can try to parse everything using a single line, but the risk exists you forget to subtract the start index of the length to get the substring (mid) value.

    Example I quickly wrote:
    vb Code:
    1. Public Class Configuration
    2.         Sub New(ByVal SettingsFile As String)
    3.             Me.Load(SettingsFile)
    4.         End Sub
    5.  
    6.         Public Sub Load(ByVal SettingsFile As String)
    7.             If System.IO.File.Exists(SettingsFile) Then
    8.                 Try
    9.                     Dim reader As New System.IO.StreamReader(SettingsFile)
    10.                     Do While reader.Peek <> -1
    11.                         Dim textline As String = reader.ReadLine
    12.                         'verify the line is valid
    13.                         If textline.Contains("[") AndAlso textline.Contains("'") Then
    14.                             Dim settingname As String = textline.Remove(0, textline.IndexOf("[") + 1)
    15.                             settingname = settingname.Substring(0, settingname.IndexOf("]"))
    16.                             Dim value As String = textline.Remove(0, textline.IndexOf("value=") + 6).Trim("'").Trim()
    17.  
    18.                             'set the correct variable based on the name
    19.                             Select Case settingname.ToLower
    20.                                 Case "editor text color"
    21.                                     Me.CTColor = value
    22.                                 Case "editor background color"
    23.                                     Me.CBColor = value
    24.                                 Case "application title color"
    25.                                     Me.CFormTitleColor = value
    26.                                 Case "top menu color"
    27.                                     Me.CTMenuColor = value
    28.                                 Case "bottom status menu color"
    29.                                     Me.CBMenuColor = value
    30.                                 Case "font type"
    31.                                     Me.CFontType = value
    32.                                 Case "font size"
    33.                                     Me.CFontSize = value
    34.                                 Case "tab spacing size"
    35.                                     Me.CTabSpacer = value
    36.                                 Case "drag drop files"
    37.                                     Me.CDragDrop = value
    38.                                 Case "always on top"
    39.                                     Me.COnTop = value
    40.                                 Case "word wrap"
    41.                                     Me.CWordWrap = value
    42.                                 Case Else
    43.                                     Debug.WriteLine("Setting not found: " & settingname & " with value " & value)
    44.                             End Select
    45.                         End If
    46.                     Loop
    47.                     reader.Close()
    48.                 Catch ex As Exception
    49.                     Debug.WriteLine(ex.Message)
    50.                 End Try
    51.             End If
    52.         End Sub
    53.  
    54.         Public CBColor As String
    55.         Public CTColor As String
    56.         Public CFormTitleColor As String
    57.         Public CTMenuColor As String
    58.         Public CBMenuColor As String
    59.         Public CFontType As String
    60.         Public CFontSize As String
    61.         Public CTabSpacer As String
    62.         Public CDragDrop As String
    63.         Public COnTop As String
    64.         Public CWordWrap As String
    65.     End Class

    Code:
    Dim c As New Configuration("Config.ini")
    I really recommend you use a class to store you configuration information. It makes your code look a lot better, especially if you have to reload your settings multiple times during runtime.

    Alternatively you could add a single hashtable and write key/value pairs to it. This way it would work with any variable:
    Code:
                        Table = New Hashtable()
                        Dim reader As New System.IO.StreamReader(SettingsFile)
                        Do While reader.Peek <> -1
                            Dim textline As String = reader.ReadLine
                            'verify the line is valid
                            If textline.Contains("[") AndAlso textline.Contains("'") Then
                                Dim settingname As String = textline.Remove(0, textline.IndexOf("[") + 1)
                                settingname = settingname.Substring(0, settingname.IndexOf("]"))
                                Dim value As String = textline.Remove(0, textline.IndexOf("value=") + 6).Trim("'").Trim()
    
                                Table.Add(settingname, value)
                            End If
                        Loop
                        reader.Close()
    Code:
    Dim CTextColor As String = Table.Item("Editor Text Color")
    EDIT

    Kaliman your code has one issue: If the reader reaches the end another line is read; thus at least one "Nothing" line is read (by user code, not the reader) which could cause null reference exceptions.
    You'd have to add another If block around it checking if the newly read line is nothing. It makes code longer, thus I like to stick with the Peek method.

    Code:
         Do
              OriginalString = ConfigFile.ReadLine()
              If OriginalString Is Nothing Then
                   Exit Do
              Else
                   NewString = Mid(OriginalString, InStr(OriginalString, "'"), Len(OriginalString) - InStr(OriginalString, "'") - 1)           
                   Select Case NewString
                        Case "Editor Text Color"
                             CTColor = NewString           
                             RichTextBox1.ForeColor = ColorTranslator.FromHtml(CTColor)
                        Case "Editor Background Color"
                             CBColor = NewString
                             RichTextBox1.BackColor = ColorTranslator.FromHtml(CBColor)
    
                   End Select
              End If
         Loop

  13. #13
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Reading Data From Lines of .ini File

    I might as well add my two cents

    you could use For loops:
    Code:
     Dim sLineOfText As String = ""
            Dim bValueFound As Boolean = False
    
            Dim iSingleQuoteIndex As Integer = 0
            Dim sValue As String = ""
            Dim sFileName As String = ""
            If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
    
    
    
                sFileName = OpenFileDialog1.FileName()
    
                Dim sr As System.IO.StreamReader = New System.IO.StreamReader(sFileName)
    
                Do While sr.Peek >= 0
                    sLineOfText = sr.ReadLine
                    bValueFound = False 'set flag to false
    
                    For x As Integer = 0 To sLineOfText.Length
                        If CBool(sLineOfText.IndexOf("'")) Then ' 
                            iSingleQuoteIndex = sLineOfText.IndexOf("'") '
                            sValue = sLineOfText.Substring(iSingleQuoteIndex + 1) '
    
                            For y As Integer = 0 To sValue.Length '
    
                                If CBool(sValue.IndexOf("'")) Then '
                                    sValue = sLineOfText.Substring(iSingleQuoteIndex + 1, sValue.IndexOf("'")) ' 
                                    '
    
                                    bValueFound = True
                                    Debug.Print(sValue)
                                    Exit For
                                End If
                            Next
                        End If
    
                        If bValueFound Then Exit For 'reset flag for jumping out this For/Next and back into the Do loop, if it is still going
                    Next
                Loop
    
                sr.Close()
    
    
            End If
    or 2 If Statements:
    Code:
       Dim sLineOfText As String = ""
            Dim iSingleQuoteIndex1 As Integer = 0
            Dim iSingleQuoteIndex2 As Integer = 0
            Dim sValue As String = ""
            Dim sFileName As String = ""
            If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
    
                sFileName = OpenFileDialog1.FileName()
    
                Dim sr As System.IO.StreamReader = New System.IO.StreamReader(sFileName)
    
                Do While sr.Peek >= 0
                    sLineOfText = sr.ReadLine
    
    
                    If sLineOfText.Contains("'") Then ' 
                        iSingleQuoteIndex1 = sLineOfText.IndexOf("'") '
                        sValue = sLineOfText.Substring(iSingleQuoteIndex1 + 1) '
                        If sValue.Contains("'") Then
                            iSingleQuoteIndex2 = sValue.IndexOf("'")
                            sValue = sLineOfText.Substring(iSingleQuoteIndex1 + 1, iSingleQuoteIndex2) '
    
    
                            Debug.Print(sValue)
    
                        End If
    
                    End If
    
                Loop
    
                sr.Close()
    
    
            End If

  14. #14

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    I'm not using openfiledialog though.

    bergerkiller, your information really helped after trying several different methods, I think I finally understand what I was doing wrong from the start. I had the value's and the setting name coming out fine. I tested using a quick msgbox to get the values of both, but your code narrows mine down a bit more I think.

    Code:
    Case "tab spacing size"
    Me.CTabSpacer = value
    That I actually have set to FormTabs instead of me because it's not on the same form.

    And one more thing, could I not use:
    Code:
    Do While ConfigFile.ReadLine.StartsWith("[")
    Last edited by AceInfinity; May 23rd, 2011 at 08:40 PM.

  15. #15

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    The code I have now still doesn't seem to work. It only loops through the first setting for some reason, at least it appears that way... I just want it in a sub for now so I can understand it first.

    vb Code:
    1. Private Sub LoadDefaultConfig()
    2.  
    3.         Dim ConfigFile As New StreamReader("Config.ini")
    4.         Dim OriginalString As String = ConfigFile.ReadLine()
    5.  
    6.         Dim CBColor As String
    7.         Dim CTColor As String
    8.         Dim CFormTitleColor As String
    9.         Dim CTMenuColor As String
    10.         Dim CBMenuColor As String
    11.         Dim CFontType As String
    12.         Dim CFontSize As String
    13.         Dim CTabSpacer As Integer
    14.         Dim CDragDrop As Boolean
    15.         Dim COnTop As Boolean
    16.         Dim CWordWrap As Boolean
    17.         Try
    18.             Do While ConfigFile.ReadLine.StartsWith("[")
    19.  
    20.                 If OriginalString.Contains("[") AndAlso OriginalString.Contains("'") Then
    21.                     'Get the value of the Setting Name
    22.                     Dim SettingName As String = OriginalString.Remove(0, OriginalString.IndexOf("[") + 1)
    23.                     SettingName = SettingName.Substring(0, SettingName.IndexOf("]"))
    24.                     'Get the value of the Setting Name's  configuration Value
    25.                     Dim Value As String = OriginalString.Remove(0, OriginalString.IndexOf("value=") + 6).Trim("'").Trim()
    26.  
    27.                     Select Case SettingName.ToLower
    28.                         Case "Editor Text Color"
    29.                             CTColor = Value
    30.                             Me.RichTextBox1.ForeColor = ColorTranslator.FromHtml(CTColor)
    31.                         Case "Editor Background Color"
    32.                             CBColor = Value
    33.                             Me.RichTextBox1.BackColor = ColorTranslator.FromHtml(CBColor)
    34.                         Case "Application Title Color"
    35.                             CFormTitleColor = Value
    36.                             Me.Label1.ForeColor = ColorTranslator.FromHtml(CFormTitleColor)
    37.                             Me.TitleFilename.ForeColor = ColorTranslator.FromHtml(CFormTitleColor)
    38.                         Case "Top Menu Color"
    39.                             CTMenuColor = Value
    40.                             Me.MenuStrip1.BackColor = ColorTranslator.FromHtml(CTMenuColor)
    41.                         Case "Bottom Status Menu Color"
    42.                             CBMenuColor = Value
    43.                             Me.StatusStrip1.BackColor = ColorTranslator.FromHtml(CBMenuColor)
    44.                         Case "Font Type"
    45.                             CFontType = Value
    46.                             Me.RichTextBox1.Font = New System.Drawing.Font(RichTextBox1.Text, CFontType)
    47.                         Case "Font Size"
    48.                             CFontSize = Value
    49.                             Me.RichTextBox1.Font = New System.Drawing.Font(RichTextBox1.Text, CFontSize)
    50.                         Case "Tab Spacing Size"
    51.                             CTabSpacer = Value
    52.                             FormTabs.NumericUpDown1.Value = CTabSpacer
    53.                         Case "Drag Drop Files"
    54.                             CDragDrop = Value
    55.                             Me.RichTextBox1.AllowDrop = CDragDrop
    56.                         Case "Always On Top"
    57.                             COnTop = Value
    58.                             Me.TopMost = Value
    59.                         Case "Word Wrap"
    60.                             CWordWrap = Value
    61.                             Me.RichTextBox1.WordWrap = Value
    62.                         Case Else
    63.                             Debug.WriteLine("Setting not found: " & SettingName & " with the value '" & Value & "'")
    64.                     End Select
    65.  
    66.                 End If
    67.  
    68.             Loop
    69.  
    70.             ConfigFile.Close()
    71.         Catch ex As Exception
    72.             Debug.WriteLine(ex.Message)
    73.         End Try
    74.  
    75.     End Sub

  16. #16
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Reading Data From Lines of .ini File

    Hi Ace, the opendialog was mainly for my benefit to make quit coding to post for you

    I'm looking at this real quick:
    Code:
    Select Case SettingName.ToLower
                            Case "Editor Text Color"
    The Case to test for would be
    "editor text color"

    wouldn't it?
    -
    edit:
    Place
    Code:
    Dim OriginalString As String = ""
    at top where you initialize it.
    -

    Place
    Code:
    OriginalString = ConfigFile.ReadLine
    within the Do loop at top.

    -
    This will feed the next line into originalString
    Hope that
    helps
    Last edited by proneal; May 23rd, 2011 at 09:52 PM. Reason: forgot to add

  17. #17
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Reading Data From Lines of .ini File

    Seems like you are doing much more than necessary when there is My.Settings to store, retrieve and save options or use an XML configuration file to store, retrieve and save options.

  18. #18
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Reading Data From Lines of .ini File

    I agree with you on that KEvin, when it involves many settings like this, and I am sure it will grow -lol, xml is nice, clean and fast.
    My.settings was like a godsend when I found that when .Net came out.
    -
    It's fun too, though, to search through the strings like Ace is doing.

    I like it all.
    I'm too easy
    Last edited by proneal; May 23rd, 2011 at 09:59 PM. Reason: i Misspelled -:P

  19. #19

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    I started using an xml app.config file, but I want to be able to use a .ini file. I don't want to use the app settings either, I want a settings file seperate from the application as a .ini file extension to get the settings as an older method of configuration.

    And yes, I did remove the ToLower so that it didn't read only lower case strings, but I didn't know that got posted with the first code of mine I posted lol, my fault. proneal you fixed the code finally though lol, After doing that it finally went through the lines of my .ini file, thanks

    I spent way too long on this part of my application, through trying different methods and troubleshooting. For what I want the settings to do though, a .ini file seems more appropriate since xml isn't designed to be written to from what i've heard. xml was also invented so it could handle more advanced data for an application's configuration, but for what i'm using it for I don't see a need to use it. I could have used application settings, but I want a more "visual" configuration instead. You can view all of the settings directly from the .ini file in this case, and I can create more setting's files If I wanted to, or add them all onto the same one i'm creating with a little bit of work.
    Last edited by AceInfinity; May 23rd, 2011 at 10:30 PM.

  20. #20
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Reading Data From Lines of .ini File

    It's your program Ace.
    YOU call the shots, lol
    Fun to code, aint it..
    No matter which way/method -when it works, it makes life that much grander.
    I'm pathetic, i know

    -
    Glad you got it going Ace.

  21. #21

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    I love coding though, the feeling after finally figuring something out is good. I just don't like it when I'm stuck after a while of trying different methods and troubleshooting.

    lol for some reason though I need to figure out why my loop is checking every second line. I thought it wasn't validating some lines, until I checked the ini file itself, and I figured out that the pattern it was making was skipping every second line. So I still have a minor problem, but i'm that much closer....

    My code so far:
    Last edited by AceInfinity; May 23rd, 2011 at 11:23 PM.

  22. #22

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    vb Code:
    1. 'Sets all of the defaults from the configuration file
    2.     Private Sub LoadDefaultConfig()
    3.  
    4.         Dim ConfigFile As New StreamReader("Config.ini")
    5.  
    6.         'Dim OriginalString As String = ConfigFile.ReadLine()
    7.         Dim OriginalString As String = ""
    8.  
    9.         Dim CBColor As String
    10.         Dim CTColor As String
    11.         Dim CFormTitleColor As String
    12.         Dim CTMenuColor As String
    13.         Dim CBMenuColor As String
    14.         Dim CFontType As String
    15.         Dim CFontSize As String
    16.         Dim CTabSpacer As String
    17.         Dim CDragDrop As String
    18.         Dim COnTop As String
    19.         Dim CWordWrap As String
    20.  
    21.         Try
    22.             Do Until Not ConfigFile.ReadLine.StartsWith("[")
    23.                 OriginalString = ConfigFile.ReadLine
    24.  
    25.                 If OriginalString.Contains("[") AndAlso OriginalString.Contains("'") Then
    26.                     'Get the value of the Setting Name
    27.                     Dim SettingName As String = OriginalString.Remove(0, OriginalString.IndexOf("[") + 1)
    28.                     SettingName = SettingName.Substring(0, SettingName.IndexOf("]"))
    29.                     'Get the value of the Setting Name's  configuration Value
    30.                     Dim Value As String = OriginalString.Remove(0, OriginalString.IndexOf("value=") + 6).Trim("'").Trim()
    31.  
    32.                     MsgBox(SettingName & ": " & Value)
    33.  
    34.                     Select Case SettingName
    35.                         Case "Editor Text Color"
    36.                             CTColor = Value
    37.                             Me.RichTextBox1.ForeColor = ColorTranslator.FromHtml(CTColor)
    38.  
    39.                         Case "Editor Background Color"
    40.                             CBColor = Value
    41.                             Me.RichTextBox1.BackColor = ColorTranslator.FromHtml(CBColor)
    42.  
    43.                         Case "Application Title Color"
    44.                             CFormTitleColor = Value
    45.                             Me.Label1.ForeColor = ColorTranslator.FromHtml(CFormTitleColor)
    46.                             Me.TitleFilename.ForeColor = ColorTranslator.FromHtml(CFormTitleColor)
    47.  
    48.                         Case "Top Menu Color"
    49.                             CTMenuColor = Value
    50.                             Me.MenuStrip1.BackColor = ColorTranslator.FromHtml(CTMenuColor)
    51.  
    52.                         Case "Bottom Status Menu Color"
    53.                             CBMenuColor = Value
    54.                             Me.StatusStrip1.BackColor = ColorTranslator.FromHtml(CBMenuColor)
    55.  
    56.                         Case "Font Type"
    57.                             CFontType = Value
    58.                             'Me.RichTextBox1.Font = New System.Drawing.Font(RichTextBox1.Text, CFontType)
    59.  
    60.                         Case "Font Size"
    61.                             CFontSize = Value
    62.                             'Me.RichTextBox1.Font = New System.Drawing.Font(RichTextBox1.Text, CFontSize)
    63.  
    64.                         Case "Tab Spacing Size"
    65.                             CTabSpacer = CInt(Value)
    66.                             'FormTabs.NumericUpDown1.Value = CTabSpacer
    67.  
    68.                         Case "Drag Drop Files"
    69.                             CDragDrop = CBool(Value)
    70.                             'Me.RichTextBox1.AllowDrop = CDragDrop
    71.  
    72.                         Case "Always On Top"
    73.                             COnTop = CBool(Value)
    74.                             'Me.TopMost = COnTop
    75.  
    76.                         Case "Word Wrap"
    77.                             CWordWrap = CBool(Value)
    78.                             'Me.RichTextBox1.WordWrap = CWordWrap
    79.                         Case Else
    80.                             Debug.WriteLine("Setting not found: " & SettingName & " with the value '" & Value & "'")
    81.                     End Select
    82.                 End If
    83.  
    84.             Loop
    85.  
    86.         Catch ex As Exception
    87.             MsgBox(ex.Message)
    88.         End Try
    89.         ConfigFile.Close()
    90.     End Sub

    I never understand the mycode for the vbcode, whenever I use [ HIGHLIGHT ][ /HIGHLIGHT ] as the surrounding brackets for my code it just turns my code into a bunch of red text, yet when I use the button for VBCode, and put my code between those exact same 2 mycodes, it works...

    Edit: now that i'm looking at this code, I think the problem is that with the trim, it's moving the second line of text beside the line is just read by removing a trailing space, and so when it moves to the next line, the line after the one it's suppose to read gets moved up because the second line gets bumped to the same line as the setting it just read. I'll edit and test it out.

    Update: Nope, my theory was incorrect, I tried not using the trim function and tried

    Code:
    Dim Something As String = OriginalString.Remove(0, OriginalString.IndexOf("value=") + 6)
    Dim Value As String = Something.Replace("'", "")
    But nothing changed, still reads every second line in the .ini.... If I ever get this figured out i'll provide a download link for my program if it doesn't go against any rules here for everyone lol.

    hmm I should also fix my font size falue and convert it to Single, so that that .25 doesn't show up. never noticed it before, I just figured that I got the saving the .ini file part down that I'd move onto the read part.
    Last edited by AceInfinity; May 23rd, 2011 at 11:38 PM.

  23. #23

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    Finally!! got it

    solution:
    Code:
    While Not ConfigFile.EndOfStream
    Using a while loop instead.

    One problem i'm having now:

    Code:
    Case "Font Size"
                                CFontSize = CSng(Value)
                                'Me.RichTextBox1.Font = New System.Drawing.Font(RichTextBox1.Text, CFontSize)
                                Me.RichTextBox1.Font = New System.Drawing.Font(RichTextBox1.Text, CFontSize)
    
                            Case "Font Type"
                                CFontType = Value
                                'Me.RichTextBox1.Font = New System.Drawing.Font(RichTextBox1.Text, CFontType)
                                Me.RichTextBox1.Font = New System.Drawing.Font(RichTextBox1.Text, FontName.CfontType)
    The code needed to define a new font type is Richtextbox.font = New System.Drawing.Font(RichTextBox1.Text, FONTSIZE, FONTTYPE)

    And since I dont have a font size as a value, how can I put in a font type without having that value within that case? When I debug it, it keeps saying that it cannot convert "courier new" to single, so I get the value of the font type, but it's trying to parse it as data for the font size.

    I couldn't put 2 values into the .ini file on the same line to get them both at once or it would mess up all of the trimming to get my settings variable and my values.
    Last edited by AceInfinity; May 24th, 2011 at 12:58 AM.

  24. #24
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Reading Data From Lines of .ini File

    Haven't had time to open the IDE and try things out for you.
    It might be alright to initialize all these variables with DEFAULT values.
    This is good because you wouldn't have to carry the ini with your package setup.
    The program could write the ini file on it's first start up. with all the default values.
    Then it can just replace the values as needed with the Options/Settings form- at some later time when User decides to change things up.
    -
    All the best to you Ace!

  25. #25

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: Reading Data From Lines of .ini File

    Ahh, lol you and me think alike Thats the way I just finished coding it out. I just let it run LoadDefaultConfig() on form load, and if the file used for loading the default config doesn't exist (Config.ini)... Then it will load the program with the applications default settings, and create that ini file with the default app settings for the file. I also have a button that will open the file directly into the editor for manual modification if someone wants to do it that way, but now the app should do everything for you.

    Here's a download if any of you would like to give it a test Hopefully i'm allowed to provide a sample of what i'm working on like this because I haven't been able to find the rules on this forum very easily.

    http://www.mediafire.com/?75ztgt8d08fzv1g

    Thanks for all of the help. I'm still continuing my development on this project. When you run it, it will create a config file in the same directory as the app, so I'll create a setup.exe to place it in the program folders location on install like I did with version 3.0. You can create a folder manually though in program folder, and then create a shortcut on the desktop so that you don't have to deal with the config file taking up space on your desktop with the application.

    I figured out the font variables by parsing the data to labels that i've kept hidden on the actual form, so once the loop has gone through all the lines, and has discovered the value for the font size and type, it will use both of those in the font code as a new system.drawing.font. Maybe not the best way to do it, but it works, and nothing is visible to the user.

    Next thing i'm adding will be a "Sort" function for lines within the editor, for alphabetical sorting.
    Last edited by AceInfinity; May 24th, 2011 at 05:26 AM.

  26. #26
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Reading Data From Lines of .ini File

    Quote Originally Posted by AceInfinity View Post
    I started using an xml app.config file, but I want to be able to use a .ini file. I don't want to use the app settings either, I want a settings file seperate from the application as a .ini file extension to get the settings as an older method of configuration.

    And yes, I did remove the ToLower so that it didn't read only lower case strings, but I didn't know that got posted with the first code of mine I posted lol, my fault. proneal you fixed the code finally though lol, After doing that it finally went through the lines of my .ini file, thanks

    I spent way too long on this part of my application, through trying different methods and troubleshooting. For what I want the settings to do though, a .ini file seems more appropriate since xml isn't designed to be written to from what i've heard. xml was also invented so it could handle more advanced data for an application's configuration, but for what i'm using it for I don't see a need to use it. I could have used application settings, but I want a more "visual" configuration instead. You can view all of the settings directly from the .ini file in this case, and I can create more setting's files If I wanted to, or add them all onto the same one i'm creating with a little bit of work.
    First off good to hear you got things working but wanted to address what you said about xml isn't designed to be written to. Check out the attached VS2008 project which demos how easy it is to read/write to and from a XML settings file. In the demo the file is stored in the app folder but could easily be stored any place you wanted. Also note in the form load event there is a good deal of assertion in that if there are no values set on first time usage it will provide default values. Lastly for an actual app all the code shown would be housed in a class that you would create once and use all over the app. Time to create this demo was roughly 30 minutes.

    Example from the demo for read/write font information
    Code:
    Dim FontInformation = _
    ( _
       From B In Document...<Font> _
       Select Family = B.<Type>.Value, _
              Size = If(String.IsNullOrEmpty(B.<Size>.Value), 8, _
                        CSng(B.<Size>.Value))).FirstOrDefault
    
    If FontInformation IsNot Nothing Then
       Dim MyFont = New Font(FontInformation.Family, _
                             FontInformation.Size, _
                             Me.Font.Style)
       FontDialog1.Font = MyFont
    End If
    
    If FontDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
       Dim Query = (From B In Document...<EditorSettings> Select B.<Font>).FirstOrDefault
       Query.<Type>.Value = FontDialog1.Font.FontFamily.Name
       Query.<Size>.Value = FontDialog1.Font.Size.ToString
       Document.Save(SettingsFile)
    End If
    Demo settings file
    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <ApplicationSettings>
      <MainForm>
        <BackGroundColor>Red</BackGroundColor>
      </MainForm>
      <EditorSettings>
        <Font>
          <Type>Microsoft Sans Serif</Type>
          <Size>9</Size>
        </Font>
        <AlwaysOnTop>True</AlwaysOnTop>
      </EditorSettings>
    </ApplicationSettings>
    Attached Files Attached Files

  27. #27

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: [RESOLVED] Reading Data From Lines of .ini File

    Yeah I know it's possible, i'm a programmer, but I don't specifically code in VB.net. XML can be written to, but I just said it wasn't really designed for that, specifically for app settings for an application. Since XML can hold more advanced and complex data, if you have some of that information stored into an XML file, it shouldn't be that easily changed. So the more common way of initializing a settings file is through an .ini file, and by keeping an XML file dedicated to the more advanced data for the application config.

  28. #28
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: [RESOLVED] Reading Data From Lines of .ini File

    Quote Originally Posted by AceInfinity View Post
    Yeah I know it's possible, i'm a programmer, but I don't specifically code in VB.net. XML can be written to, but I just said it wasn't really designed for that, specifically for app settings for an application. Since XML can hold more advanced and complex data, if you have some of that information stored into an XML file, it shouldn't be that easily changed. So the more common way of initializing a settings file is through an .ini file, and by keeping an XML file dedicated to the more advanced data for the application config.
    ini files are not the recommended method to store settings anymore, that is old news. Examples, your project and solution files all use XML to store settings, Microsoft Office 2007 stores some settings in XML while other settings in the system registry. Lastly Adobe Fireworks stores settings in XML. Not to beat an old dog to death but XML is the way to go, no API's to read/write to them or code you have to bend over backwards to understand.

    Any ways it is your choice and will leave it at that, just wanted to give you a good current method to read/write your settings.

  29. #29

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: [RESOLVED] Reading Data From Lines of .ini File

    That's exactly what I meant though, I understand the difference between both, but for someone to edit an xml file to change settings like boolean values for true or false on things like word wrap, always on top, detect urls, etc... Including color values and an integer value for the tab spacing on my app would be chaotic, and the greater the chances of someone screwing up. I wanted a config file that was easy to edit manually and xml was the worst way to go in this case. It's designed to hold more complex configuration data. Originally .ini files did that, then Microsoft came out with the registry, and xml was invented, xml is too complex in this case.

    Your example of Adobe fireworks... Do you really think that a notepad application like this is as advanced as that? lol. People also don't go ahead and edit that xml file directly. This .ini file i've associated with my app was far better suited for the job. If I need a config file for more complex information i'll use xml, but chances are people won't be editing that xml file for their user settings, instead of the ini file that i've created because it's simplistic.

  30. #30
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: [RESOLVED] Reading Data From Lines of .ini File

    Quote Originally Posted by AceInfinity View Post
    I wanted a config file that was easy to edit manually
    This was never specified in your original question.

    INI or XML configuration files are not supposed to be edited manually but instead by the application or program that uses them.

    Quote Originally Posted by AceInfinity View Post
    Including color values and an integer value for the tab spacing on my app would be chaotic, and the greater the chances of someone screwing up.
    This is why people should not be editing them. If the developer wants to edit them then fine, if they screw it up then there is something really wrong if this is the developer who wrote the code. Better to have a options dialog to change information no matter if the config file is INI or XML.

    In regards to
    Quote Originally Posted by AceInfinity View Post
    Do you really think that a notepad application like this is as advanced as that?
    That is not the issue, instead a developer should be consistent in how they code which in this case is reading settings from a configuration file.

  31. #31

    Thread Starter
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 2011
    Posts
    696

    Re: [RESOLVED] Reading Data From Lines of .ini File

    This was never specified in your original question.
    INI or XML configuration files are not supposed to be edited manually but instead by the application or program that uses them.

    It should make sense to you though that having a user manually edit a config file would make it easier for them to edit the .ini i'm giving them instead of a whole bunch of xml having parts that don't require any editing. Only the bottom half that includes the application settings.

    .ini file's are created to be written to manually or programmatically. Please don't come on my thread and tell me any different because i'm more familiar with ini than I am in xml.

    This is why people should not be editing them. If the developer wants to edit them then fine, if they screw it up then there is something really wrong if this is the developer who wrote the code. Better to have a options dialog to change information no matter if the config file is INI or XML.
    my comment there was about xml, not ini at all. ini file's aren't complicated if they are meant to be config files for specific things, whereas you can't really control all of the extra stuff that isn't to be changed in an xml file.

    If they screw it up on my app, it will revert to the default application setting automatically, so that's already handled. If I had that for xml, that wouldn't be the case, things would screw up.

    That is not the issue, instead a developer should be consistent in how they code which in this case is reading settings from a configuration file.
    It is the issue, i'm not asking the ini file to carry out anything complicated, so thats why I would never need to have used xml instead. xml was created because ini couldn't deal with complex tasks. so the registry was also invented at the time by microsoft.

    what are you saying about consistency here? consistent in what? I am consistent in my code but between xml and ini just because you use xml doesn't mean you have to always use xml, and vice versa. Consistency is important in programming, but not in this case if i'm understanding this correctly.

    Using xml for advanced applications and for even a basic button press application is completely unorthodox. You don't have to make things more complicated on the program side of the spectrum if it's not needed. If I was to give someone access to edit a button press program through xml and compare to ini, that's a difference of quite a few lines of code that they would have to look through to find the actual configuration part of it. xml is not necessary here.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width