Jump to content

Recommended Posts

Posted (edited)

Boas,

Precisava de uma ajudinha,

Queria ler a primeira linha do ficheiro TXT e depois a 3 palavra (725540N) e a 5 palavra (470055N)

No codigo seguinte já esta a ler a linha 1, só falta ler as palavras.

Ficheiro TXT:

0N 728340N [b]725540N[/b] 470823N [b]470055N[/b] 2465291N 2218062N 2461770N 2216563N
735472547  2216563N2216563N
OFF 87340578t8hr  2216563N

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       Dim FILE_NAME As String = "c:\teste.txt"

       Dim TextLine As String

       If System.IO.File.Exists(FILE_NAME) = True Then

           Dim objReader As New System.IO.StreamReader(FILE_NAME)

           Do While objReader.Peek() <> -1

               TextLine = TextLine & objReader.ReadLine() & vbNewLine

           Loop

           TextBox1.Text = TextLine
           TextBox2.Text = TextLine

       Else

           MsgBox("File Does Not Exist")

       End If
   End Sub
Edited by thoga31
Formatação do tópico + GeSHi
  • Replies 65
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Posted

Boas,

podes partir a string lida pelo caracter do espaço. Algo assim (não testado):

Dim palavras As String() = TextLine.Split(" ")

Depois deves conseguir aceder à terceira e quinta palavra acedendo ao array palavras.

Convem é certificares-te que o array tem mais de 5 palavras antes de acederes.

Posted (edited)

Não conseguiste porque... ?

Aqui está um exemplo:

	Dim FILE_NAME As String = "c:\teste.txt"
	Dim TextLine As String = ""

	If System.IO.File.Exists(FILE_NAME) = True Then

		TextLine = System.IO.File.ReadAllText(FILE_NAME)

		Dim palavras As String() = TextLine.Split(" ")

		If palavras.Length > 4 Then
			TextBox1.Text = palavras(2)
			TextBox2.Text = palavras(4)
		End If
	Else
		MsgBox("File Does Not Exist")
	End If
Edited by nelsonr
Posted (edited)

Só um pequeno aparte, que a solução está bem encaminhada e pouco mais há a acrescentar.

Porque é que tanta gente insiste em fazer a verificação de um Boolean numa estrutura If? O "= True" é completamente desnecessário e redundante, apenas enche a vista e o processador de coisas desnecessárias. 😉

' Redundante:
If System.IO.File.Exists(FILE_NAME) = True Then

' Mais correcto...
If System.IO.File.Exists(FILE_NAME) Then
If Not System.IO.File.Exists(FILE_NAME) Then
Edited by thoga31

Knowledge is free!

Posted

Eu não uso, apenas utilizei o exemplo do OP.

No entanto há que prefira muitas vezes soluções redundantes para facilitar a interpretação. Principalmente para quem não está habituado à linguagem.

Posted (edited)

Boas,

Tentei assim e não apareceu nada nas TextBoxs, tambem não tem erros,

//
Dim FILE_NAME As String = "c:\teste.txt"
        Dim TextLine As String = ""
        Dim palavras As String() = TextLine.Split(" ")
        Dim objReader As New System.IO.StreamReader(FILE_NAME)

        If System.IO.File.Exists(FILE_NAME) Then
            If Not System.IO.File.Exists(FILE_NAME) Then

                TextLine = System.IO.File.ReadAllText(FILE_NAME)


                Do While objReader.Peek() <> -1

                    TextLine = TextLine & objReader.ReadLine() & vbNewLine

                Loop

                If palavras.Length > 10 Then

                    TextBox1.Text = palavras(7)
                    TextBox2.Text = palavras(9)

                End If
            Else

                MsgBox("File Does Not Exist")

            End If
        End If
   End Sub
Edited by ribeiro55
Posted (edited)

Boas,

grandes trocas que andaste a fazer.

então estás a dividir a TextLine logo apos a definição, que está vazia.

Dim TextLine As String = ""
Dim palavras As String() = TextLine.Split(" ")

Estás a verificar se o ficheiro existe e se existir, estás a verificar se não existe?

If System.IO.File.Exists(FILE_NAME) Then
		    If Not System.IO.File.Exists(FILE_NAME) Then

Estás a ler o ficheiro duas vezes. O ReadAllText já lê o conteúdo todo do ficheiro para a variavel, não precisas do restante

TextLine = System.IO.File.ReadAllText(FILE_NAME)

Do While objReader.Peek() <> -1
  TextLine = TextLine & objReader.ReadLine() & vbNewLine
Loop

Experimentaste o código que coloquei lá em cima?

Não precisavas de alterar nada

Edited by nelsonr
Posted
Agora so tenho que acertar as palavras.

// If palavras.Length > 10 Then

isto corresponde ao tamanho das palavras?

Corresponde ao tamanho do array palavras (quantos elementos tem), que por sua vez será o número de palavras que está no ficheiro

Posted (edited)

esta a dar erro aqui

       If System.IO.File.Exists(FILE_NAME) = True Then

mas ja veriquei e o ficheiro existe

Edited by thoga31
Correcção da linguagem (GeSHi)
Posted (edited)

Testei com o primeiro codigo que postei aqui no topico e funcionou.

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       Dim FILE_NAME As String = "d:\Teste\Teste"

       Dim TextLine As String

       If System.IO.File.Exists(FILE_NAME) = True Then

           Dim objReader As New System.IO.StreamReader(FILE_NAME)

           Do While objReader.Peek() <> -1

               TextLine = TextLine & objReader.ReadLine() & vbNewLine

           Loop

           TextBox1.Text = TextLine
           TextBox2.Text = TextLine

       Else

           MsgBox("File Does Not Exist")

       End If
   End Sub

Com este codigo ele funciona, não precisa da extensao.

Edited by thoga31
Correcção da linguagem (GeSHi)

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.