locked
Search with Stream reader VB2008 RRS feed

  • Question


  • Hello..


    I have a little problem with my application..

    I use 5 textbox named :

    rname '''' name of user
    rsurname ''' surname of user
    rage ''' age of user
    remail '''' email of user
    rwebsite '''' website of user

    When the user fill the textboxes and press the save button the content will be saved in a txt file like 'rname.txt'.

    I used streamwriter for this, it works fine, and it's saved like this :

    [user name :]rname[end user name]
    [user surname]rsurname[end user surname]
    [user age]rage[end user age] etc....

    I add the newfile in a combobox..

    By selecting a line in the combobox i want to read the content of the file i used this code :

     
    Code: 
    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged 
            If ComboBox1.SelectedIndex > -1 Then 
     
                'Get a StreamReader to read the text file 
                Dim reader As System.IO.StreamReader 
     
                reader = System.IO.File.OpenText(System.IO.Path.Combine("websites/"String.Format("{0}", ComboBox1.SelectedItem))) 
     
             
                ClientInfoBox.Text = reader.ReadToEnd 
     
     
                'Close the stream 
                reader.Close() 
     
            End If  


    It works fine and add the content of the file in the richtextbox named ClientInfoBox.

    Here is what i need :

    I need to read the file line by line and search the text between
    [user name :]
    and
    [end user name] and put the result in rname.text

    search the text between
    [user surname]
    and
    [end user surname] and put the result in rsurname.text

    etc...

    Any suggestions will be appreciated.
    Thanks.

    • Edited by houssem-hj Monday, September 15, 2008 3:18 AM Add code
    Monday, September 15, 2008 3:18 AM

Answers

  • Well, XML is not faster than a texfile, but smaller xml files are about as fast as texfiles, because xml uses plain text.

    XML is only more professional because it is a standard format.  It has been recommended by the by the World Wide Web Consortium (W3C) as a standardized text markup language.

    With XML, you basically define your own tags and sub-tags to store your data.  Since the text markup is stored in plain text, it is possible to edit an xml file in a plain text editor, like Notepad.

    The problem with XML in .Net is that the methods and classes have become somewhat convoluted, and not all methods will work with all of the .Net Framework versions.

    For very large xml files, methods exist in the .Net Framework to navigate thru the xml file to locate a specific node or tag, or text.

    For small xml files, depending on how you store the data, one simple method to parse data is to loop thru an xml reader, and use a switch case/select case to locate the data you are looking for.   Another way is to store multiple attributes for one or two tags, and then when you read the file you can collect the attributes, and then look thru them for your data.

    Here's a basic example that stores and gets string data from an xml file.

     
     
        Sub SaveXML()  
            Try 
                Dim DocPath As String = "C:\Test\UserData.xml" 
                If Not IO.Directory.Exists(IO.Path.GetDirectoryName(DocPath)) Then 
                    IO.Directory.CreateDirectory(IO.Path.GetDirectoryName(DocPath))  
                End If 
                Dim Doc As New Xml.XmlDocument  
                Dim Root As Xml.XmlElement  
                Dim SubNode As Xml.XmlNode  
                Dim PI As Xml.XmlProcessingInstruction  
                ' Write XML declaration.  
                PI = Doc.CreateProcessingInstruction("xml""version='1.0'")  
                Doc.AppendChild(PI)  
                ' Write comment.  
                Doc.AppendChild(Doc.CreateComment("User info for " & Application.ProductName & "Application."))  
                ' Write root element.  
                Root = Doc.CreateElement("UserInfo")  
                Doc.AppendChild(Root)  
                ' Name  
                SubNode = Doc.CreateNode(Xml.XmlNodeType.Element, "Name""")  
                SubNode.InnerText = "The name of the user" 
                Root.AppendChild(SubNode)  
                ' Surname  
                SubNode = Doc.CreateNode(Xml.XmlNodeType.Element, "SurName""")  
                SubNode.InnerText = "The Surname of the user" 
                Root.AppendChild(SubNode)  
                ' age  
                SubNode = Doc.CreateNode(Xml.XmlNodeType.Element, "Age""")  
                SubNode.InnerText = "33" 
                Root.AppendChild(SubNode)  
                ' email  
                SubNode = Doc.CreateNode(Xml.XmlNodeType.Element, "Email""")  
                SubNode.InnerText = "Address@email.addr" 
                Root.AppendChild(SubNode)  
                ' website  
                SubNode = Doc.CreateNode(Xml.XmlNodeType.Element, "Website""")  
                SubNode.InnerText = "http://www.SomeWebpage.com/BogusPage/" 
                Root.AppendChild(SubNode)  
                Doc.Save(DocPath)  
                '  
                ' Open folder.  
                System.Diagnostics.Process.Start(IO.Path.GetDirectoryName(DocPath))  
            Catch ex As Exception  
                MessageBox.Show(ex.ToString)  
            End Try 
     
        End Sub 
     
        Sub GetXML()  
            Dim DocPath As String = "C:\Test\UserData.xml" 
            Try 
                If IO.Directory.Exists(IO.Path.GetDirectoryName(DocPath)) AndAlso IO.File.Exists(DocPath) Then 
                    Dim s As String 
                    Dim Reader As Xml.XmlReader  
                    Reader = Xml.XmlReader.Create(DocPath)  
                    Reader.MoveToElement()  
                    While Reader.Read  
                        If Reader.NodeType = Xml.XmlNodeType.Element Then 
                            Select Case Reader.Name.ToLower  
                                Case "name" 
                                    s = Reader.ReadString  
                                    MsgBox("Name: " & s)  
                                Case "surname" 
                                    s = Reader.ReadString  
                                    MsgBox("SurName: " & s)  
                                Case "age" 
                                    s = Reader.ReadString  
                                    MsgBox("Age: " & s)  
                                Case "email" 
                                    s = Reader.ReadString  
                                    MsgBox("Email: " & s)  
                                Case "website" 
                                    s = Reader.ReadString  
                                    MsgBox("WebSite: " & s)  
                            End Select 
                        End If 
                    End While 
                    Reader.Close()  
                End If 
            Catch ex As Exception  
                MessageBox.Show(ex.ToString)  
            End Try 
        End Sub 
    • Edited by Matt Fomich Monday, September 15, 2008 8:07 AM
    • Marked as answer by houssem-hj Monday, September 15, 2008 9:04 AM
    Monday, September 15, 2008 7:58 AM

All replies

  •  Four options:

    You can read one line at a time; see example at:

          File.OpenText Method on MSDN Site

    You can read the all the text into a string and then use regular expressions to search based on the patterns you are using. 

           MSDN Regular Expressions

    You can save the data into a .xml file containing an element for each user, and for each user elements for user name, sur name, age, email, and web site.  The reason I suggest this is that it may be easier to write the data to file and read it using xml.  If you are using Visual Basic 2008, it will be very easy because you can use xml literals for the task.

    You can use a database.  That is the common solution for what you want to do.


    Mike McIntyre Senior Developer / Partner aZ Software Developers
    Monday, September 15, 2008 4:01 AM
  • Hi  Mike.

    Thanks for your reply.

    I tried to modify the lines of the file like this :

    [user name :]rname
    [user surname]rsurname
    [user age]rage


    instead of :


    [user name :]rname[end user name]
    [user surname]rsurname[end user surname]
    [user age]rage[end user age] etc....

    then i try
        reader = System.IO.File.OpenText(System.IO.Path.Combine("websites/"String.Format("{0}", ComboBox1.SelectedItem))) 
     
                ' Use Do While... Loop to read the file until nothing is returned 
                Do While reader.Peek <> -1 
                    MyString = reader.ReadLine() ' Read a line from the file and assign it to the value of the String Variable 
     
                    If MyString.StartsWith("[user name :]"Then ' Check what the line from the file starts with 
                        MySplit = MyString.Split("]"c) ' Split the line at the ] character 
                        Mytitle &= MySplit(1) & vbCrLf ' add the second Element of the String Array to the String which will be written to the file 
                        rtitle.Text = Mytitle 

    and it works..

    I'm still new with VB, so i didn't try XML before,

    If using XML is faster and more professional i will be glad if there's a little example showing how to write and read with xml files.

    Any code ???

    Monday, September 15, 2008 4:22 AM
  • Well, XML is not faster than a texfile, but smaller xml files are about as fast as texfiles, because xml uses plain text.

    XML is only more professional because it is a standard format.  It has been recommended by the by the World Wide Web Consortium (W3C) as a standardized text markup language.

    With XML, you basically define your own tags and sub-tags to store your data.  Since the text markup is stored in plain text, it is possible to edit an xml file in a plain text editor, like Notepad.

    The problem with XML in .Net is that the methods and classes have become somewhat convoluted, and not all methods will work with all of the .Net Framework versions.

    For very large xml files, methods exist in the .Net Framework to navigate thru the xml file to locate a specific node or tag, or text.

    For small xml files, depending on how you store the data, one simple method to parse data is to loop thru an xml reader, and use a switch case/select case to locate the data you are looking for.   Another way is to store multiple attributes for one or two tags, and then when you read the file you can collect the attributes, and then look thru them for your data.

    Here's a basic example that stores and gets string data from an xml file.

     
     
        Sub SaveXML()  
            Try 
                Dim DocPath As String = "C:\Test\UserData.xml" 
                If Not IO.Directory.Exists(IO.Path.GetDirectoryName(DocPath)) Then 
                    IO.Directory.CreateDirectory(IO.Path.GetDirectoryName(DocPath))  
                End If 
                Dim Doc As New Xml.XmlDocument  
                Dim Root As Xml.XmlElement  
                Dim SubNode As Xml.XmlNode  
                Dim PI As Xml.XmlProcessingInstruction  
                ' Write XML declaration.  
                PI = Doc.CreateProcessingInstruction("xml""version='1.0'")  
                Doc.AppendChild(PI)  
                ' Write comment.  
                Doc.AppendChild(Doc.CreateComment("User info for " & Application.ProductName & "Application."))  
                ' Write root element.  
                Root = Doc.CreateElement("UserInfo")  
                Doc.AppendChild(Root)  
                ' Name  
                SubNode = Doc.CreateNode(Xml.XmlNodeType.Element, "Name""")  
                SubNode.InnerText = "The name of the user" 
                Root.AppendChild(SubNode)  
                ' Surname  
                SubNode = Doc.CreateNode(Xml.XmlNodeType.Element, "SurName""")  
                SubNode.InnerText = "The Surname of the user" 
                Root.AppendChild(SubNode)  
                ' age  
                SubNode = Doc.CreateNode(Xml.XmlNodeType.Element, "Age""")  
                SubNode.InnerText = "33" 
                Root.AppendChild(SubNode)  
                ' email  
                SubNode = Doc.CreateNode(Xml.XmlNodeType.Element, "Email""")  
                SubNode.InnerText = "Address@email.addr" 
                Root.AppendChild(SubNode)  
                ' website  
                SubNode = Doc.CreateNode(Xml.XmlNodeType.Element, "Website""")  
                SubNode.InnerText = "http://www.SomeWebpage.com/BogusPage/" 
                Root.AppendChild(SubNode)  
                Doc.Save(DocPath)  
                '  
                ' Open folder.  
                System.Diagnostics.Process.Start(IO.Path.GetDirectoryName(DocPath))  
            Catch ex As Exception  
                MessageBox.Show(ex.ToString)  
            End Try 
     
        End Sub 
     
        Sub GetXML()  
            Dim DocPath As String = "C:\Test\UserData.xml" 
            Try 
                If IO.Directory.Exists(IO.Path.GetDirectoryName(DocPath)) AndAlso IO.File.Exists(DocPath) Then 
                    Dim s As String 
                    Dim Reader As Xml.XmlReader  
                    Reader = Xml.XmlReader.Create(DocPath)  
                    Reader.MoveToElement()  
                    While Reader.Read  
                        If Reader.NodeType = Xml.XmlNodeType.Element Then 
                            Select Case Reader.Name.ToLower  
                                Case "name" 
                                    s = Reader.ReadString  
                                    MsgBox("Name: " & s)  
                                Case "surname" 
                                    s = Reader.ReadString  
                                    MsgBox("SurName: " & s)  
                                Case "age" 
                                    s = Reader.ReadString  
                                    MsgBox("Age: " & s)  
                                Case "email" 
                                    s = Reader.ReadString  
                                    MsgBox("Email: " & s)  
                                Case "website" 
                                    s = Reader.ReadString  
                                    MsgBox("WebSite: " & s)  
                            End Select 
                        End If 
                    End While 
                    Reader.Close()  
                End If 
            Catch ex As Exception  
                MessageBox.Show(ex.ToString)  
            End Try 
        End Sub 
    • Edited by Matt Fomich Monday, September 15, 2008 8:07 AM
    • Marked as answer by houssem-hj Monday, September 15, 2008 9:04 AM
    Monday, September 15, 2008 7:58 AM
  • One other thing.

    If you do coding on projects that will be used by other people, I would use xml for storing and retrieving data, instead of text files, or else I would use a data base file.  The reason texfiles are not recommended is that when someone else needs that data from the textfile, they don't know how it is supposed to be stored and retrieved.  At least with XML anyone can open and parse the file, as long as it is a well written xml file.


    Monday, September 15, 2008 8:05 AM
  • Hi Matt..

    Thank you very much,

    This code will be very hepful.

    I will change to xml and let you know.

    Thanks again.


    Monday, September 15, 2008 9:04 AM