views:

1032

answers:

6

Hey everyone,

I want my program to read certain text in a text file. For example if I have a text file that contains the following info..

acc=blah
pass=hello

I want my vb.net application to get that the account variable is equal to blah, and the password variable is equal to hello.

Can anyone tell me how to do this?

Thanks

+3  A: 

Have a look at this article

Reading and writing text files with VB.NET

Wile reading the file line by line, you can use String.Split Method with the splitter being "=", to split the string into param name, and param value.

astander
A: 

You can't really selectively read a certain bit of information in the file exclusively. You'll have to scan each line of the file and do a search for the string "pass=" at the beginning of the line. I don't know VB but look up these topics:

  1. File readers (espically ones that can read one line at a time)
  2. String tokenizers/splitting (as Astander mentioned)
  3. File reading examples
monksy
A: 

My suggestion: you use XML. The .NET framework has a lot of good XML tools, if you're willing to make the transition to put all the text files into XML, it'll make life a lot easier.

Not what you're looking for, probably, but it's a cleaner solution than anything you could do with plain text (outside of developing your own parser or using a lower level API).

new123456
+2  A: 

Looks like you've got an INI file of some kind... The best way to read these is using the *PrivateProfile* functions of the windows API, which means you can actually have a proper full INI file quite easily for anything you need. There is a wrapper class here you may like to use.

Microsoft recommends that you use the registry to store this sort of information though, and discourages use of INI files.

If you wish to just use a file manually with the syntax you have, it is a simple case of splitting the string on '=' and put the results into a Dictionary. Remember to handle cases where the data was not found in the file and you need a default/error. In modern times though, XML is becoming a lot more popular for data text files, and there are lots of libraries to deal with loading from these.

KernelJ
+2  A: 

Here is a quick little bit of code that, after you click a button, will:

  1. take an input file (in this case I created one called "test.ini")
  2. read in the values as separate lines
  3. do a search, using regular expressions, to see if it contains any "ACC=" or "PASS=" parameters
  4. then write them to the console

here is the code:

Imports System.IO
Imports System.Text.RegularExpressions

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim strFile As String = "Test.INI"
    Dim sr As New StreamReader(strFile)
    Dim InputString As String

    While sr.Peek <> -1
        InputString = sr.ReadLine()
        checkIfContains(InputString)
        InputString = String.Empty
    End While
    sr.Close()
End Sub

Private Sub checkIfContains(ByVal inputString As String)
    Dim outputFile As String = "testOutput.txt"
    Dim m As Match
    Dim m2 As Match
    Dim itemPattern As String = "acc=(\S+)"
    Dim itemPattern2 As String = "pass=(\S+)"

    m = Regex.Match(inputString, itemPattern, _
                    RegexOptions.IgnoreCase Or RegexOptions.Compiled)
    m2 = Regex.Match(inputString, itemPattern2, _
                    RegexOptions.IgnoreCase Or RegexOptions.Compiled)
    Do While m.Success
        Console.WriteLine("Found account {0}", _
                          m.Groups(1), m.Groups(1).Index)
        m = m.NextMatch()
    Loop
    Do While m2.Success
        Console.WriteLine("Found password {0}", _
                          m2.Groups(1), m2.Groups(1).Index)
        m2 = m2.NextMatch()
    Loop
End Sub

End Class
Diakonia7
This code works in drawing out the parameters asked for from a text file. Downvoting is effective in pointing out a problem in a solution. But feedback should be given as well in order to elaborate for the benefit of others reading the posted answer as well as the answerer.
Diakonia7
Do you have a source code for this?
Kevin
Nvm. about the source code.. i got it to work. I just have one question. How can I hold the data from the m.groups(1).... where the program writes the data to, into a variable?
Kevin
Diakonia7
It still gives me the error that it can't be converted to string...
Kevin
Kevin
Diakonia7
Haha, I'm already enjoying christmas. But, in the string.concat function, it will display the number of characters after the word. How can I fix this?
Kevin
A: 

Have you thought about getting the framework to handle it instead?

If you add an entry into the settings tab of the project properties with name acc, type string, scope user (or application, depending on requirements) and value pass, you can use the System.Configuration.ApplicationSettingsBase functionality to deal with it.

 Private _settings As My.MySettings
   Private _acc as String
   Private _pass as String
   Public ReadOnly Property Settings() As System.Configuration.ApplicationSettingsBase
        Get
            If _settings Is Nothing Then
                _settings = New My.MySettings
            End If
            Return _settings
        End Get
    End Property
    Private Sub SetSettings()
        Settings.SettingsKey = Me.Name
        Dim theSettings As My.MySettings
        theSettings = DirectCast(Settings, My.MySettings)
        theSettings.acc=_acc
        theSettings.pass=_pass        
        Settings.Save()
    End Sub
    Private Sub GetSettings()
        Settings.SettingsKey = Me.Name
        Dim theSettings As My.MySettings
        theSettings = DirectCast(Settings, My.MySettings)
        _acc=theSettings.acc
        _pass=theSettings.pass
    End Sub

Call GetSettings in whatever load event you need, and SetSettings in closing events

This will create an entry in the application.exe.config file, either in your local settings \apps\2.0\etc etc directory, or your roaming one, or if it's a clickonce deployment, in the clickonce data directory. This will look like the following:-

<userSettings>
        <MyTestApp.My.MySettings>
            <setting name="acc" serializeAs="String">
                <value>blah</value>
            </setting>
        <setting name="pass" serializeAs="String">
                <value>hello</value>
        </setting>
    </MyTestApp.My.MySettings>
   </userSettings>
Doogie