Solved

Find specific text within a txt file?

Posted on 2014-03-06
6
322 Views
Last Modified: 2014-03-06
Hi,
I am creating a simple program to allow me to save my passwords in a text file.
I can create the file (is a plain text file), I can add new 'Concepts' and its 'Password' but now I need to search for an specific 'Concept' and display its password.

In the code below, "recordatorio" corresponds to the concept, and "clave_recordatorio" corresponds to its password.

The code I have, until now, is the following:

Code to Save new 'Concepts' with their 'Password'
    Private Sub btnGuardarClave_Click(sender As Object, e As EventArgs) Handles btnGuardarClave.Click
        'agregamos informacion al archivo contenedor de claves
        Dim ruta2 As String = CStr(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
        Dim archivo2 As String = "archivo.txt"
        Dim addinfo As New System.IO.StreamWriter(ruta2 & "\" & archivo2, True)

        Dim recordatorio As String = CStr(txtRecordatorio.Text)
        Dim clave_recordatorio As String = CStr(txtClaveRecordatorio.Text)

        addinfo.WriteLine("[Recordatorio]: " & recordatorio)
        addinfo.WriteLine("[Clave]: " & clave_recordatorio)

        addinfo.Close()
        MsgBox("Archivo actualizado")
        Me.Close()
    End Sub

Open in new window

The result of the text file Is as follows:

[Recordatorio]: Telefonica
[Clave]: zxcvb
[Recordatorio]: VTR
[Clave]: 1234
[Recordatorio]: Computador Casa
[Clave]: asdf
[Recordatorio]: Computador Trabajo
[Clave]: qwerty

With this text file, if I want to know the password of 'Computador Casa', the program should say 'asdf'.

Code to Read the password for a 'Context':
No code yet, I have the form with 2 textboxes, one for the Concept (txtConcept), and the other for the Password (txtPassword) (read from the text file).
0
Comment
Question by:José Perez
  • 4
  • 2
6 Comments
 
LVL 25

Accepted Solution

by:
SStory earned 250 total points
Comment Utility
#1: I would NEVER store passwords in a plain text file. You should think of encrypting the data at least.

#2 If I were saving this I'd do username,password or username tab password on each line:
  addinfo.WriteLine(string.format("{0}{1}{2}",recordatorio,vbTab,clave_recordatorio))

Then when reading it in. You just do the reverse.

        Dim Parts() As String
        Dim strLine As String
        Dim sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader("yourfilename")
        While sr.Peek <> -1
            strLine = sr.ReadLine()
            Parts = strLine.Split(vbTab)
            MsgBox(String.Format("Recordatorio: {0}  Clave {1}",Parts(0),Parts(1)
        End While

        sr.Close()

Open in new window


Obviously replace the "yourfilename" with your path as you did when writing it.
In the real world you'd want to try/catch/finally and be sure to clean up, handle exceptions and close.

Espero que le ayuda. Dios le bendiga.
0
 
LVL 2

Author Comment

by:José Perez
Comment Utility
A propósito, Parts(0) y Parts(1) están, ambos, guardando "[Recordatorio: ] Telefonica", pero ninguno guarda la clave.

Inicialmente me arroja un error en 'vbTab', debo modificarlo y agregar 'CChar' como lo sugiera el VStudio?
Parts = strLine.Split(CChar(vbTab))

Open in new window


Finalmente, si agrego el 'CChar' corre peroarroja un error 'Index was outside the bounds of the array'

Que Dios te bendiga, también.
0
 
LVL 2

Author Comment

by:José Perez
Comment Utility
Te adjunto una imagen del archivo y del mensaje que obtengo de los cambios que me indicaste...
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 2

Author Comment

by:José Perez
Comment Utility
Fixed!
This is how finally I solved:
        Dim Parts() As String
        Dim strLine As String

        'agregamos informacion al archivo contenedor de claves
        Dim ruta3 As String = CStr(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
        Dim archivo3 As String = "archivo.txt"

        Dim sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(ruta3 & "\" & archivo3)
        While sr.Peek <> -1
            strLine = sr.ReadLine() 'leemos linea del archivo
            Parts = strLine.Split(CChar(vbTab))
            If Parts(0) = CStr(txtRecordatorio.Text) Then
                'MsgBox(String.Format("Recordatorio: {0}  Clave {1}", Parts(0), Parts(1)))
                txtClave.Text = Parts(1)
            End If
        End While

        sr.Close()
    End Sub

Open in new window

0
 
LVL 2

Author Closing Comment

by:José Perez
Comment Utility
I made some arrangements to what was indicated by the developer.
0
 
LVL 25

Expert Comment

by:SStory
Comment Utility
Lo siento a veces escribimos codigo de la mente sin probarlo y faltemos una cosita.

Me alegre que le ayude.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Paging GridView 7 32
Crystal Report for VS2013 17 35
Exception in Log4Net 1 17
How to Get total minutes between two hours 4 26
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

763 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

6 Experts available now in Live!

Get 1:1 Help Now