Usuário com melhor resposta
Escrever em .txt usando vb.net

Pergunta
-
Ola . No meu navegador para usar a função do histórico criei um .txt file no caminho :
C:\Users\Windows_Vista\AppData\Histórico.txt
Na form3 (janela onde é exibido o histórico) tem uma listbox1
Tou a usar este código:
If System.IO.File.Exists("C:\Users\Windows_Vista\AppData\Histórico.txt") = True Then Dim escrever As StreamWriter Dim caminho As String = "C:\Users\Windows_Vista\AppData\Histórico.txt" escrever = File.AppendText(caminho) escrever.WriteLine(ComboBox1.Text) escrever.Flush() escrever.Close() ElseIf My.Computer.FileSystem.DirectoryExists("C:\Users\Windows_Vista\AppData\Histórico.txt") = False Then Dim LOL As DialogResult = MsgBox("Um ficheiro não foi encontrado. Pretende reparar ?", "Erro crítico", MessageBoxIcon.Error, MessageBoxButtons.OK) Dim escrever As StreamWriter Dim caminho As String = "C:\Users\Windows_Vista\AppData\Histórico.txt" If LOL = Windows.Forms.DialogResult.Yes Then escrever = File.CreateText(caminho) End If
Ao abrir a form recebo o erro que o ficheiro .txt ja ta aberto noutro programa. Ja reiniciei o problema mantem
Alguma sugestão ?
O meu objetivo ______ criar um sistema operativo
Respostas
-
veja vc não está fazendo dispose no file por isso da esse erro, faz assim
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); StringBuilder sb = new StringBuilder(); foreach (string txtName in Directory.EnumerateFiles(mydocpath,"*.txt")) { using (StreamReader sr = new StreamReader(txtName)) { sb.AppendLine(txtName.ToString()); sb.AppendLine("= = = = = ="); sb.Append(sr.ReadToEnd()); sb.AppendLine(); sb.AppendLine(); } } using (StreamWriter outfile = new StreamWriter(mydocpath + @"\AllTxtFiles.txt")) { outfile.Write(sb.ToString()); }
Não esqueça de usar o componente </> na barra para posta seu código. Microsoft MCPD,MCTS,MCC
- Marcado como Resposta Harley Araujo quarta-feira, 18 de abril de 2012 13:24
Todas as Respostas
-
-
-
veja vc não está fazendo dispose no file por isso da esse erro, faz assim
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); StringBuilder sb = new StringBuilder(); foreach (string txtName in Directory.EnumerateFiles(mydocpath,"*.txt")) { using (StreamReader sr = new StreamReader(txtName)) { sb.AppendLine(txtName.ToString()); sb.AppendLine("= = = = = ="); sb.Append(sr.ReadToEnd()); sb.AppendLine(); sb.AppendLine(); } } using (StreamWriter outfile = new StreamWriter(mydocpath + @"\AllTxtFiles.txt")) { outfile.Write(sb.ToString()); }
Não esqueça de usar o componente </> na barra para posta seu código. Microsoft MCPD,MCTS,MCC
- Marcado como Resposta Harley Araujo quarta-feira, 18 de abril de 2012 13:24
-