Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET Read Certain text in a text file

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

like image 992
lab12 Avatar asked Dec 13 '09 18:12

lab12


People also ask

How do I read a text file in Visual Basic?

To read from a text file Use the ReadAllText method of the My. Computer. FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.

How do I read a .TXT file?

How to open a TXT file. You can open a TXT file with any text editor and most popular web browsers. In Windows, you can open a TXT file with Microsoft Notepad or Microsoft WordPad, both of which come included with Windows.

What is StreamReader in Visual Basic?

StreamReader handles text files. We read a text file in VB.NET by Using StreamReader. This will correctly dispose of system resources and make code simpler. The best way to use StreamReader requires some special syntax.


1 Answers

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
like image 61
Dostee Avatar answered Sep 28 '22 00:09

Dostee