Solved

Evaluating a text file

Posted on 2006-06-24
23
377 Views
Last Modified: 2013-11-18
Hi,

I want to read the content of a text file and put the text in a structured way in some variables (maybe arrays).
The text file looks like

variable1 = content
variable2 = "content content"
variable3 = content1 variable3a = content 2 variable 3b = content3

All three above mentioned possibilities could occur. After reading the text file linie by line I have to check whether a certain variable is in the text file and what it value is. If there are more than one variable in one line like in the last example I have to check: "variable3 is in the text file. Is there also variable3a and / 3b set?".

How can I do this with VB 2005 Express Edition?
0
Comment
Question by:moellert
  • 12
  • 6
  • 4
  • +1
23 Comments
 
LVL 8

Expert Comment

by:bman9111
ID: 16977367
I would just do something like this


       Dim file As IO.StreamReader
        Dim line As String
        dim variable1 as string
        file = New System.IO.StreamReader("C:\filetoread.txt")
        While file.Peek <> -1 'look at the file
            line = file.ReadLine()
            if line.indexof("content") = true then
                 variable1 = line
else if.....
end if
        End While

        file.Close()

or make a simple arraylist to store the data. i hope I am understanding u correctly....




0
 
LVL 9

Expert Comment

by:jrscherer
ID: 16977585
What do you want to do with the data? Do you want to keep the structure as in the file? Can you explain the second example; what means "Content Content".
Is content a string, or do you need to convert it into a different data type?
Jack.net
0
 
LVL 2

Author Comment

by:moellert
ID: 16978237
My program consists of some forms which a user can use to create that text file. Just think of a form asking you for your username, surname, street, zip, town and male/female. All fields are textfields, dropdown lists or checkboxes. After entering all data and clicking generate the text file is generated in in simliar format like this:
username = Tom
surname = Smith
Street = "some street" number = 1
town = mytown zip = 123456
male = true

Sometimes the value could be in "" sometimes not.
Now I want to read the file line by line to open it again in my program and evaluate all variable. After opening it my program should show the form with already filled in text/dropdown/checkbox.


0
 
LVL 2

Author Comment

by:moellert
ID: 16978266
One thing I've forgotten: Some lines start with an ; to include some comment. These lines have to be skipped.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 16979096
Is there any particular reason you picked that file format?  It will make reading it back in difficult...

Have you considered putting your data into a class and then writing it out using XML?  This would make a consistent format that is still easy to read and will be much easier to read back into your in a consistent manner.
0
 
LVL 2

Author Comment

by:moellert
ID: 16979516
There is no chance of changing the file format as it is used by a special type of computer to read its config.
0
 
LVL 8

Expert Comment

by:bman9111
ID: 16979571
is what I stated have anything to do with what u are looking for??
0
 
LVL 2

Author Comment

by:moellert
ID: 16979693
It is a start but there are a few different possibilites how the read line could look like. See my last comments.
0
 
LVL 8

Expert Comment

by:bman9111
ID: 16979715
just use this code


Dim file As IO.StreamReader
        Dim line As String
        dim variable1 as string
        file = New System.IO.StreamReader("C:\filetoread.txt")
        While file.Peek <> -1 'look at the file
            line = file.ReadLine()
            if line.contains("whatever") = true then
                 variable1 = line
else if.....
end if
if line.contains(";") then
'skip
end if
        End While

        file.Close()


This will read the text file I would just look at line and write whatever clause u need to do...

0
 
LVL 2

Author Comment

by:moellert
ID: 16979726
but I cannot put the whole line in variable1. Normaly I have to put onyl the part right to the equal sign in variable 1 and sometime there are more than one "content" in one line. Eg.
username = Tom
surname = Smith
Street = "some street" number = 1
town = mytown zip = 123456
male = true

In this case I have to put in variable user the value Tom, in variable name the value Smith, in variable street the value "some street" and in variable number tha value 1, and so on....

0
 
LVL 8

Expert Comment

by:bman9111
ID: 16979973
dont need to put the whole line in a variable...all u need to do is read the line and then pick the portion out that u would like..... then store that in a variable.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 2

Author Comment

by:moellert
ID: 16980375
how?
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 16981041
In your examples you have:

    aaa = bbb ccc ddd = eee fff = "ggg" hhh = "iii jjj" ...

Where "aaa" and "ccc" are variable names and "bbb" and "ddd" are the values.  It seems that you have may spaces in the "value" portion of the data with or without quotes.

To consistently parse this data we need to be sure that certain conditions are ALWAYS true.

To this end, can you please answer the following questions?...

(1) Will the VARIABLE names always NOT have spaces in them?

(2) Will there ever be an "=" equals sign INSIDE one the the VALUES?

    aaa = "bbb=ccc"
0
 
LVL 2

Author Comment

by:moellert
ID: 16981727
1. Variables will never have a space
2. there will be never an equal sign inside values
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 16986473
How about something like this?...

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private ht As New Hashtable

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim filename As String = "c:\someFile.txt"
        Dim sr As New System.IO.StreamReader(filename)
        Dim inputLine As String
        Dim vals() As String
        Dim i As Integer
        Dim key, value As String
        Dim lastSpace As Integer

        ht = New Hashtable
        inputLine = sr.ReadLine
        While Not (inputLine Is Nothing)
            vals = inputLine.Split("=".ToCharArray)

            For i = 0 To vals.GetUpperBound(0)
                vals(i) = vals(i).Trim

                If i = 0 Then
                    key = vals(0)
                ElseIf i < vals.GetUpperBound(0) Then
                    lastSpace = vals(i).LastIndexOf(" ")
                    value = vals(i).Substring(0, lastSpace).Trim

                    ht.Add(key, value)

                    key = vals(i).Substring(lastSpace).Trim
                Else
                    value = vals(i)
                    ht.Add(key, value)
                End If
            Next

            inputLine = sr.ReadLine
        End While
        sr.Close()


        ' display the results...
        For Each de As DictionaryEntry In ht
            Debug.WriteLine(de.Key & " = " & de.Value)
        Next
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim key, value As String
        key = "zip"
        If ht.ContainsKey(key) Then
            value = ht.Item(key)
            MessageBox.Show(key & " = " & value, "Value found", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            MessageBox.Show(key, "Value not found", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

End Class
0
 
LVL 2

Author Comment

by:moellert
ID: 16988004
Idle Mind, this is really very very close. Great work. There are two issues:
1. The code stops when there is a variable more than once (see "Connect" in below example file)
2. The code does not return the correct value if there are more than one variables in one line. (see "Timezone" in below example file)

Here is an example of an original text file I need to be read and evaluated:


;*************************************************************
;*                                                           *
;*          This  file was generated with the         *
;*                Configuration File Generator               *
;*                                                           *
;*************************************************************

autoload=1
EnableLocal=yes
Privilege=Low
Bootorder=HNN

;*************************************************************
;*                          General 2                        *
;*************************************************************

keyboard=de
Language=de_DE.UTF-8

;*************************************************************
;*                           Display                         *
;*************************************************************

Resolution=1280x1024
DeskColor="255 128 0"

;*************************************************************
;*                             Time                          *
;*************************************************************

Timeformat="24-hour format"
TimeZone=CET ManualOverride=yes Daylight=yes

;*************************************************************
;*                           Network                         *
;*************************************************************

SignOn=No
DefaultUser=UsE_lAsT_lOgOn

;*************************************************************
;*                             ICA                           *
;*************************************************************

Seamless=yes
MPinStartMenu=yes

;-------------------------------------------------------------
;-                        ICA Session 1                      -
;-         Each line but the last must end with a ' \'       -
;-------------------------------------------------------------

CONNECT=ICA \
BrowserIP=sadc \
MPServer=sadvcxv \
Application="xcvyxc" \
Icon=yxcv \
Ping=yes \
Sound=yes \
LocalCopy=no

;-------------------------------------------------------------
;-                        ICA Session 2                      -
;-         Each line but the last must end with a ' \'       -
;-------------------------------------------------------------

CONNECT=ICA \
BrowserIP=sadc \
MPServer=sadvcxv \
Application="xcvyxc" \
Icon=yxcv \
Ping=yes \
Sound=yes \
LocalCopy=no

;-------------------------------------------------------------
;-                        ICA Session 2                      -
;-         Each line but the last must end with a ' \'       -
;-------------------------------------------------------------

CONNECT=ICA \
BrowserIP=sadc \
MPServer=sadvcxv \
Application="xcvyxc" \
Icon=yxcv \
Ping=yes \
Sound=yes \
LocalCopy=no
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 16988330
It works...here is my output:

SignOn = No
Resolution = 1280x1024
ManualOverride = yes
LocalCopy = no
MPServer = sadvcxv \
Language = de_DE.UTF-8
DefaultUser = UsE_lAsT_lOgOn
autoload = 1
Daylight = yes
TimeZone = CET
DeskColor = "255 128 0"
BrowserIP = sadc \
MPinStartMenu = yes
Application = "xcvyxc" \
keyboard = de
Icon = yxcv \
Ping = yes \
Timeformat = "24-hour format"
Sound = yes \
Privilege = Low
CONNECT = ICA \
Bootorder = HNN
EnableLocal = yes
Seamless = yes

The variables "TimeZone", "ManualOverride" and "Daylight" are all present with the correct values.

The variables are not listed in the same order as the text file.  A HashTable orders its values based on the hash value of each key.

What should happen if a "key" is present already?  Will the duplicate key always have the same value?



Here is the modified code to ignore comments and prevent duplicate key entries:
(The Button2 code is to demonstrate how to retrieve a value by key)

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private ht As New Hashtable

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim filename As String = "c:\someFile.txt"
        Dim sr As New System.IO.StreamReader(filename)
        Dim inputLine As String
        Dim vals() As String
        Dim i As Integer
        Dim key, value As String
        Dim lastSpace As Integer

        ht = New Hashtable
        inputLine = sr.ReadLine
        While Not (inputLine Is Nothing)
            If Not inputLine.StartsWith(";") Then
                vals = inputLine.Split("=".ToCharArray)

                For i = 0 To vals.GetUpperBound(0)
                    vals(i) = vals(i).Trim

                    If i = 0 Then
                        key = vals(0)
                    ElseIf i < vals.GetUpperBound(0) Then
                        lastSpace = vals(i).LastIndexOf(" ")
                        value = vals(i).Substring(0, lastSpace).Trim

                        If Not ht.ContainsKey(key) Then
                            ht.Add(key, value)
                        End If

                        key = vals(i).Substring(lastSpace).Trim
                    Else
                        value = vals(i)

                        If Not ht.ContainsKey(key) Then
                            ht.Add(key, value)
                        End If
                    End If
                Next
            End If

            inputLine = sr.ReadLine
        End While
        sr.Close()


        ' display the results...
        For Each de As DictionaryEntry In ht
            Debug.WriteLine(de.Key & " = " & de.Value)
        Next
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim key, value As String
        key = "ManualOverride"
        If ht.ContainsKey(key) Then
            value = ht.Item(key)
            MessageBox.Show(key & " = " & value, "Value found", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            MessageBox.Show(key, "Value not found", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

End Class
0
 
LVL 2

Author Comment

by:moellert
ID: 16993829
Idle Mind,

one last question (hopefully):
How can I convert the keys and value all to lowercase before evaluating?
eg. in my test file there is "SignOn=yes" and I check for "signon". So this will fail.

Thomas
 
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 16993952
You can convert the line to all lowercase before proceeding with the rest of the code:

    ...
    If Not inputLine.StartsWith(";") Then
        inputLine = inputLine.ToLower                          ' <----- convert to lowercase
        vals = inputLine.Split("=".ToCharArray)

        ...

    End If
    ...
0
 
LVL 2

Author Comment

by:moellert
ID: 16995533
Idle Mind,

in my text file there is a statement called "Bootorder=XYZ". How can I divide the value XYZ in value1=X, value2=Y and value3=Z?
This is only necessary with bootorder.
I want to divide this when evaluating the file not during the read process.
eg:
        If ht.ContainsKey("bootorder") Then
            value = ht.Item("bootorder")
-> divide the value here
            Select Case value1
                Case "h"
                    do something
                Case "u"
                    do something
                Case "p"
                    do something
             End Select

            Select Case value1
                Case "h"
                    do something
                Case "u"
                    do something
                Case "u"
                    do something
             End Select

            Select Case value2
                Case "h"
                    do something
                Case "u"
                    do something
                Case "p"
                    do something
             End Select

           End If

If you want I can open a new question for this and donate some more points.

Thanks
Thomas
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 16997237
So it is simply three single characters combined together?

    ...
    value = ht.Item("bootorder")
    value1 = value.Substring(0,1)
    value2 = value.Substring(1,1)
    value3 = value.Substring(2,1)
    ...



0
 
LVL 2

Author Comment

by:moellert
ID: 16998980
You are my hero.

Thanks a lot
0
 
LVL 2

Author Comment

by:moellert
ID: 16999434
Idle Mind,

as there were two follow up questions I do not want to stress you I have opened a new thread.
Hopefully you can help me again

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_21901701.html

Regards
Thomas
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now