read specific text file line to string - help!

Alex_W

Member
Joined
Jan 5, 2009
Messages
22
Programming Experience
Beginner
I need to read a text file, find a line that contains "ComputerName=" then write this line to a string variable I can set to a label on my form. Does anyone have code for this?? Closest thing I have (which doesnt work) is coded:

VB.NET:
' Open file.txt with the Using statement.
        Using r As System.IO.StreamReader = New System.IO.StreamReader("file.ini")
            ' Store contents in this String.
            Dim line As String
            ' Read first line.
            line = r.ReadLine
            ' Loop over each line in file, While list is Not Nothing.
            Do While (line.Contains("ComputerName="))
                ' Add this line to list.
                line.ToString(ComputerName)
                ' Read in the next line.
                line = r.ReadLine
            Loop
        End Using
        lblComputerName.Text = ComputerName
 
Hi Alex, this is a pretty simple answer but looking at your code, I dont think a single line at all would have worked and thought it might be better to first understand what you are doing wrong.

VB.NET:
       [COLOR="seagreen"] 'Are you passing the full path to the file or just the file name?[/COLOR]
        Using r As System.IO.StreamReader = New System.IO.StreamReader("[COLOR="Red"]file.ini[/COLOR]")

            '[COLOR="seagreen"]"line" is pretty meaningless and although MS thinks 
            'intellisense does away with the need to use variable prefixes
            'you always want to make coding easier to understand at a glance
            'also it is good practice to always intialize your variables[/COLOR]
            Dim line As String
   
            line = r.ReadLine

            [COLOR="seagreen"]'Loop while the line equals "ComputerName="; doesnt make sense
            'and never even enters the loop unless the very first line
            'happens to contain ComputerName=.[/COLOR]            
            Do While (line.Contains("ComputerName="))

               [COLOR="seagreen"] 'line is already a string variable, why are you converting it to a string               'It also doesnt accept any parameters, so this wont even compile
                'What is ComputerName anyway, its not declared anywhere?
                'Even if ComputerName is a declared variable, where are you assigning a value into the variable?[/COLOR] 
                [COLOR="red"]line.ToString(ComputerName)[/COLOR]

    [COLOR="seagreen"]            'So if your line is ComputerName, 
                'your still going to read the next line/rest of the file?[/COLOR]
                line = r.ReadLine
            Loop
        End Using


        lblComputerName.Text = ComputerName
 
Last edited:
VB.NET:
        [COLOR="Blue"]Dim[/COLOR] strComputerName [COLOR="blue"]As String[/COLOR] = ""

        [COLOR="SeaGreen"]'Displays OpenDialog window[/COLOR]
        [COLOR="blue"]If [/COLOR]dlgOpen.ShowDialog <> Windows.Forms.DialogResult.OK [COLOR="blue"]Then Exit Sub[/COLOR]

        [COLOR="blue"]Using [/COLOR]rdrFile [COLOR="blue"]As New[/COLOR] IO.StreamReader(dlgOpen.FileName)
            [COLOR="blue"]Dim [/COLOR]strCurrentLine [COLOR="blue"]As String [/COLOR]= ""

            [COLOR="blue"]Do[/COLOR]
                strCurrentLine = rdrFile.ReadLine

                [COLOR="blue"]If [/COLOR]strCurrentLine.Contains("ComputerName=") [COLOR="blue"]Then[/COLOR]
                    [COLOR="SeaGreen"]'Store whole line into variable[/COLOR]
                    strComputerName = strCurrentLine
                    [COLOR="blue"]Exit Do[/COLOR]
                [COLOR="blue"]End If
            Loop Until [/COLOR]strCurrentLine [COLOR="blue"]Is Nothing[/COLOR]
        [COLOR="blue"]End Using [/COLOR][COLOR="seagreen"]'rdrFile (closes file & disposes object)[/COLOR]

        lblComputerName.Text = strComputerName
 
Do not use Hungarian notation
Otherwise? Electric chair? Or is anything from MS carved into stone and we will face hell if we do not follow?
I do like the hungarian too. Makes reading the source faster ... for me at least. Seeing strSomething I know that this is a string var without need to check the declaration/definition.

It's a question of personal preference, I think. Nobody is hurt, so we should leave that a personal choice.

BTW: Since not everybody uses VS ONLY, but maybe other languages too (like PHP), it would be difficult for a single programmer to constantly switch naming systems in his/her mind.
 
picoflop said:
Seeing strSomething I know that this is a string var without need to check the declaration/definition.
Just hover the variable and IDE will tell you the type should you be uncertain.
Otherwise? Electric chair?
Yeah, perhaps ;) I use Hungarian too sometimes, for forms with lots of controls where I need to access particular controls by code I find it easier to remember thus faster to type finding for example buttons by typing Me.btn... and textboxes with Me.txt... etc (or sometimes with other category/functionality prefix). Because the fields holding these controls is not declared anywhere accessible to read (buried in Designer generated code), one can otherwise not find these names easily.

But for variables in local code (except the limited use of private class fields of course) I don't like it much, it's like reading a type declaration every time you pass the variable name, very annoying and also distracts the actual declaration and its purpose and scope. I mentioned you can hover the variable anytime to see the type. Also, if you can't see the declaration at a glance in current screen consider refactoring the method. Some people also abstract their code by making declarations away from and outside the scope where they are used, this usually lead to much more lines of code in a method, more "detached" code, and less memory efficient code.

Opinions of course, but strongly supported by official guidelines.
 
Thanks for that Tom. Just before reading your reply I managed to adapt the original code to work although I'm certain there are unproductive bits.

I'm grabbing the ini file path from the registry, key value is put into the 'TargetDirectory' string.

So this code finds the file, reads each line until it contains "ComputerName=", copies the full line to 'ComputerNameFull' then I grab the PC name data as a substring cutting out "ComputerName=" at the start and pass to a label on my form.

One problem: some lines contain the same text, e.g. "Software" & "NewSoftware" and the last picked up seems to be returned so I tried using StartsWith() instead of Contains() but I get a runtime error!

VB.NET:
Using a As System.IO.StreamReader = New System.IO.StreamReader(TargetDirectory & "\wstdShipuser.ini")
            Dim line As String
            ' Read first line.
            line = a.ReadLine
            ' Loop over each line in file, While list is Not Nothing.
            Do While Not (line.Contains("ComputerName="))
                ' Read in the next line.
                line = a.ReadLine
                If line.Contains("ComputerName=") Then
                    ComputerNameFull = line
                    ComputerName = ComputerNameFull.Substring(13)
                End If
            Loop
        End Using
        lblComputerName.Text = "Computer Name: " & ComputerName

Help very appreciated guys, also agreed that type prefixes are best practice and easier to read code with. :D
 
There shouldn't even be a need to look at any coding, not know what something is and then have to hover a mouse over a word to figure out its datatype. This does not save any time, the opposite it wastes time. Additionally intellisense is not going to identify the scope of the object where as a single letter could identify whether a variable is local, modual or global.

Honestly MS guidelines may have dropped prefixes but I would not even hire a new developer that doesnt care enough about there coding to not use prefixes and the only explaination they can give for doing so is to save on typing... Besides showing me that the programmer is lazy and coding is sloppy, it additionally shows he does not even think of anyone else that may have to work on the same project.
 
Last edited:
Hi Alex, I see some additional problems still.

VB.NET:
            ' Read first line.
            line = a.ReadLine

            ' Loop over each line in file, While list is Not Nothing.
           [COLOR="red"] Do While Not (line.Contains("ComputerName="))[/COLOR]

                ' Read in the next line.
                line = a.ReadLine
                If line.Contains("ComputerName=") Then
                    ComputerNameFull = line
                    ComputerName = ComputerNameFull.Substring(13)
                End If
            Loop

What if the very first line in the file contains the key word "ComputerName="? It will never enter the loop or get assigned to your strComputerNameFull varabile.

One problem: some lines contain the same text, e.g. "Software" & "NewSoftware" and the last picked up seems to be returned so I tried using StartsWith() instead of Contains() but I get a runtime error!

Since the above coding doesnt mention anything about looking for "Software", Im not sure what is occurring but taking a guess here, it is storing "software" into your variable, continuing to read the rest of the file because its not exiting with the found word, and each additional line that see's Software overwrites the previous by being stored in the same variable.

Just a preference but I prefer to use String.IndexOf("ComputerName=") to search strings.
 
If you aren't worried about it being particularly efficient at runtime and you have Linq and Option Infer On, I would probably do...

Const cnstart = "ComputerName="
Dim lines = IO.File.ReadAllLines("file.ini")
Dim ComputerName = (From line in lines Where line.StartsWith(cnstart)).First.SubString(cnstart.Length)
 

Latest posts

Back
Top