Nuno Teixeira Posted December 14, 2015 at 03:07 PM Report Share #590648 Posted December 14, 2015 at 03:07 PM Olá a todos, Tenho uma listbox que lê ficheiros TXT. Tudo funciona como pretendo excepto quando o utilizador clicar na opção "Cancel" do OpenFileDialog. Nesse caso é retornado um erro pois o campo onde a path para o ficheiro fica vazio. O meu código é este: Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click OpenF.InitialDirectory = "./" OpenF.FileName = "Open a text file..." OpenF.Filter = "ONLY Text Files (*.txt) | *.txt" OpenF.ShowDialog() Dim R As New IO.StreamReader(OpenF.FileName) Dim str As String() = R.ReadToEnd().Split(New String(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)) ListBox1.Items.AddRange(str) R.Close() End Sub Já tentei tentei a opção "exit sub" mas ainda sem sucesso. Alguém qual a linha de código que está a faltar para lidar com esse problema? Obrigado. Cumprimentos Link to comment Share on other sites More sharing options...
Retsu9 Posted December 14, 2015 at 03:10 PM Report Share #590649 Posted December 14, 2015 at 03:10 PM penso que seja por fazeres isto : Dim R As New IO.StreamReader(OpenF.FileName) Dim str As String() = R.ReadToEnd().Split(New String(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)) ListBox1.Items.AddRange(str) R.Close() independentemente se selecionaste um ficheiro ou nao, possivelmente dá te o erro ao adicionar o item a listbox nao ? deverias verificar se existe ou nao ficheiro antes Link to comment Share on other sites More sharing options...
Nuno Teixeira Posted December 14, 2015 at 03:29 PM Author Report Share #590650 Posted December 14, 2015 at 03:29 PM Obrigado Retsu9, Usei um código semelhante ao que coloquei no post. A verdade é que funciona, ou seja, abre correctamente o ficheiro txt na listbox. Provavelmente não poderei verificar se o ficheiro existe ou não uma vez que é uma opção aleatória que o utilizador terá à disposição. Penso que preciso de uma linha de código do tipo: If OpenF.ShowDialog.cancel then Exit Sub End If Já fiz várias tentativas deste género mas até ao momento sem sucesso. Obrigado mais uma vez Link to comment Share on other sites More sharing options...
Retsu9 Posted December 14, 2015 at 03:37 PM Report Share #590651 Posted December 14, 2015 at 03:37 PM eu tenho este exemplo que usei recentemente para inserir imagens, tenta adaptar ao teu caso: Try open_file_imagem.Filter = "Image Files (*.bmp, *.jpg, *.png)|*.bmp;*.jpg;*.png" If open_file_imagem.ShowDialog = DialogResult.OK Then Me.pb_imgmenu.Image = Image.FromFile(open_file_imagem.FileName) End If Catch ex As Exception MsgBox("Erro: " & ex.ToString) End Try Link to comment Share on other sites More sharing options...
Nuno Teixeira Posted December 14, 2015 at 03:40 PM Author Report Share #590652 Posted December 14, 2015 at 03:40 PM Obrigado Retsu9, Vou fazer algumas adaptações e testar. Logo mais confirmo se o código resultou. Obrigado Link to comment Share on other sites More sharing options...
Retsu9 Posted December 14, 2015 at 03:47 PM Report Share #590654 Posted December 14, 2015 at 03:47 PM penso que deves efetuar esta verificação if OpenF.ShowDialog=DialogResult.OK Then Dim R As New IO.StreamReader(OpenF.FileName) Dim str As String() = R.ReadToEnd().Split(New String(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)) ListBox1.Items.AddRange(str) End IF Link to comment Share on other sites More sharing options...
Nuno Teixeira Posted December 14, 2015 at 03:51 PM Author Report Share #590659 Posted December 14, 2015 at 03:51 PM Muito Obrigado. Irei testar o código ao final da tarde e ainda hoje farei o ponto da situação. Obrigado Link to comment Share on other sites More sharing options...
He B TeMy Posted December 14, 2015 at 06:20 PM Report Share #590666 Posted December 14, 2015 at 06:20 PM (edited) Repara, tu estás a mostrar o FileDialog para o utilizador eventualmente escolher um ficheiro .txt, mas tu não estás a verificar se o ficheiro foi escolhido (DialogResult.OK) antes de tentares abrir o ficheiro na stream, daí o erro, fazer como o Retsu9 disse é o correcto. No entanto, estás basicamente a ler o ficheiro txt, não precisas de streamreader para isso, basta usares o File.ReadAllText assim: Dim str As String() = File.ReadAllText(OpenF.filename)..Split(New String(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)) Edited December 14, 2015 at 06:20 PM by He B Te My Link to comment Share on other sites More sharing options...
Nuno Teixeira Posted December 14, 2015 at 07:31 PM Author Report Share #590669 Posted December 14, 2015 at 07:31 PM Muito obrigado Retsu9 e He B Te My, O código resultou: if OpenF.ShowDialog=DialogResult.OK Then Dim R As New IO.StreamReader(OpenF.FileName) Dim str As String() = R.ReadToEnd().Split(New String(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)) ListBox1.Items.AddRange(str) End IF Tinha mesmo que fazer a verificação para que tudo funcionasse correctamente. Muito obrigado aos dois pelas dicas e pela ajuda no código. Cumprimentos Link to comment Share on other sites More sharing options...
He B TeMy Posted December 14, 2015 at 08:18 PM Report Share #590671 Posted December 14, 2015 at 08:18 PM Acabei de te dizer que n precisavas de streamreader, mesmo assim queres usar, tudo bem, mas agora parece que apagaste o Dispose() ... Link to comment Share on other sites More sharing options...
Nuno Teixeira Posted December 14, 2015 at 08:55 PM Author Report Share #590672 Posted December 14, 2015 at 08:55 PM Obrigado He B Te My, Não usei o teu código porque quando o testei dava erro. Testei novamente agora e funcionou. Ambas as soluções funcionam. Obrigado. Já agora se me puderes esclarecer uma situação (apenas para eu aprender e evoluir). Pensava que a função StreamReader servia exactamente para ler ficheiros sem permissão para podermos editar os mesmos após abertos. Em que difere a função File.ReadAllText? Obrigado mais uma vez. He B Te My, Quando falaste no Dispose() referias-te ao R.Close() ? Link to comment Share on other sites More sharing options...
He B TeMy Posted December 14, 2015 at 09:24 PM Report Share #590675 Posted December 14, 2015 at 09:24 PM (edited) Mas tu não estás a editar o ficheiro, tu estás a ler o conteúdo apenas, por isso deves usar o File.ReadAllText porque ele abre e fecha o ficheiro por ti devolvendo-te o conteúdo todo (texto) , eu dei-te um exemplo acima que faz exactamente o que o teu código está a fazer, e, tens um bónus de não ter de fechar a stream. Que eu saiba a classe StreamReader têm um método 'Dispose', era esse que estava a falar, se bem que os dois são praticamente iguais. Edited December 14, 2015 at 09:25 PM by He B Te My Link to comment Share on other sites More sharing options...
Nuno Teixeira Posted December 15, 2015 at 12:33 PM Author Report Share #590682 Posted December 15, 2015 at 12:33 PM Obrigado He B Te My Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now