Click here to Skip to main content
15,031,941 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Txt file looks similar to this:
[Test Configuration]
ObjectFileName=\\He2ntsd11\pe2003\ObjectMapFiles\Rel6.1\
[Datapool]
;DataPoolName=Test1
DataPoolName1=Test2

What should the below functions do:
1) Read all the contents of the txt file line by line.
2) As per above data first line will be [Test Configuration]. If its some thing with [] then it should skip
3) As per above data second line will be "ObjectFileName=\\He2ntsd11\pe2003\ObjectMapFiles\Rel6.1\".In this case the function
should read "=" and split "ObjectFileName" into one variable and "\\He2ntsd11\pe2003\ObjectMapFiles\Rel6.1\" into another variable.
4) As per above data third line will be [Datapool]. If its some thing with [] then it should skip
5) As per above data fourth line will be ";DataPoolName=Test1". If its some thing starting with ";" then it should skip
6) As per above data fifth line will be "DataPoolName1=Test2".In this case the function
should read "=" and split "DataPoolName1" into one variable and "Test2" into another variable.

VB
Public Shared g_DatapoolName as string
Public Shared g_DatapoolName1 as string
Public Shared g_ObjectFileName as string

Public Shared Function FileToArray(ByVal sFileName As String) As Integer
	Dim strFileName As String
    Dim arrLines As New ArrayList()
    Dim objReader As System.IO.StreamReader
	Dim iRowCount As Integer = 0 ' Variable to hold the total 
    strFileName = g_iniFile_LocationName & "\" & sFileName
	If System.IO.File.Exists( strFileName ) = True Then
    ' read the file's lines into an ArrayList
        objReader = New System.IO.StreamReader(strFileName)
        Do While objReader.Peek() <> -1
            arrLines.Add(objReader.ReadLine())
			
        Loop 
		objReader.Close()
	Else
		Console.WriteLine("'" & strFileName & "' File does not exist")
	End If

	Return iRowCount

End Function
'Procedure to pass the values to variables.
Public Shared Sub LoadIniFileValuetoGlobalVariabls(sGlobalVariableName As String, sKey_Value As String)  
    'Dim Result As String
    
    Select Case sGlobalVariableName
          
           Case "g_DataPoolName"
                 g_DataPoolName = sKey_Value
           Case "g_DataPoolName1"
                 g_DataPoolName1 = sKey_Value 
           Case "g_ObjectFileName"
                 g_ObjectFileName = sKey_Value	
          
    End Select
End Sub
Can someone help me how to split the read txt values and assign to variables.
Posted
Updated 9-Sep-13 11:04am
v2

Try reading this: Read/Write XML files, Config files, INI files, or the Registry[^]
It's in C#, but most of the code is pretty obvious.
   
Your approach to asking question is somewhat counter-productive. It's good that you show what you have done. But when you are listing your items you think you should implement, you are trying to stick to some ideas you are preoccupied with, but those ideas might be good or bad, so your reduce your chances to get help.

In fact, you need to create an effective API to store values by keys. Your keys are two-level: section — key => value. You can do two things: 1) create a compound key, section+key and use it as a key in a dictionary, 2) create a dictionary with the keys which represent section, the value of this dictionary would be another dictionary with a key representing a secondary key (left of '='). Both ways have their benefits, your choice depends on the typical volume and distribution of data. Besides, it affects the uniqueness of the key.

So, instead of array or a list, use the type System.Collections.Generic.Dictionary<key, value>:
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx[^].

Read the file line by one. Using StreamReader is just fine. As you read, detect section like vs. key=value line which you can parse using string.Split(new char[] {'='}). If the section already found in the dictionary (test it as you find a section line), add new data to the section, otherwise first create a new section. Do the same with new keys. On each step, check up if a key is already found.

The option #1 (with compound key), you will need to create a key type, which would be a struct or a class with string two data members, one representing the section name, another, the "=" key name. Override System.Object.Equals and System.Object.GetHashCode (simplest and effective implementation is: XOR hash codes of two string members). It is needed to allow using this type as an effective key of the dictionary. Please see my past answer: Object.GetHashCode() Method in C#.Net[^].

—SA
   
VB
Public Shared g_DatapoolName As String
   Public Shared g_DatapoolName1 As String
   Public Shared g_ObjectFileName As String

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

       '--- Change The Path Below To The Location Of Your Txt File
       Dim ioFile As New System.IO.StreamReader("C:\123.txt")

       Dim ioLines As String
       ioLines = ""

       '---Read All Txt File
       ioLines = ioFile.ReadToEnd

       ioFile.Close()
       ioFile.Dispose()


       '--- Split by Using The Line Feed Character
       Dim Seperate_Lines() As String = ioLines.Split(CChar(vbLf))

       '--- Determine How Many Lines Were In The Txt Document
       Dim Max As Integer = UBound(Seperate_Lines) 'Car_Transaction_TicketDataGridView.Rows.Count

       For MyCounter = 0 To Max - 1

           If Seperate_Lines(MyCounter).Contains("[") = True And Seperate_Lines(MyCounter).Contains("]") = True Then
               '---Do Nothing
               '--- Line Contains []

           ElseIf Seperate_Lines(MyCounter).Contains(";") = True Then
               '---Do Nothing
               '--- Line Contains ;

           Else
               If Seperate_Lines(MyCounter).Contains("=") = True Then
                   '--- Our Line Contains The = symbol So We'll Continue
                   Dim Parts() As String = Seperate_Lines(MyCounter).Split("=")


                   If Parts(0).Contains("ObjectFileName") = True Then
                       g_DatapoolName = Parts(1)
                   ElseIf Parts(0).Contains("DataPoolName1") = True Then
                       g_DatapoolName1 = Parts(1)
                   ElseIf Parts(0).Contains("DataPoolName") = True Then
                       g_DatapoolName = Parts(1)

                       'ElseIf Parts(0).Contains() = True Then

                   End If

               End If
           End If


       Next


   End Sub
   
I did the other way. Thanks Sergey for your code.

Public Shared Function ReadFile(ByVal sFileName As String)
Dim strFileName As String
Dim sName As String
Dim sValue As String
Dim iRowCount As Integer = 0
Dim Position As String
Dim blnFoundHeading As Boolean = False
strFileName = g_iniFile_LocationName & "\" & sFileName
Dim lstValues As New List(Of String)
Dim lines() As String = IO.File.ReadAllLines(strFileName)
For Each line As String In lines
If line.Contains("[") Then
' found the heading, now start loading the lines into the list until the next heading
blnFoundHeading = True
GoTo i:
ElseIf Trim(line) <> "" Then
Position = Instr(line, ";")
If Position = 0 Then
lstValues.Add(line.Trim)
sName = "g_" & Trim(Left(line, Instr(line,"=")-1))
Position = Instr(line,"=")+1
sValue = Trim(Mid(line, Position))
Call LoadIniFileValuetoGlobalVariabls (sName , sValue)
iRowCount = iRowCount + 1
End If
End If

i: Next
Return lstValues
End Function
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900