Abrir e salvar um arquivo texto em VB.NET

Abrir e salvar um arquivo texto em VB.NET

Talvez para algumas pessoas seja difícil abrir e salvar arquivos, mas tem uma dica legal.

Insira um form e nele coloque um textbox, dois botões de comando (cmdOpen e cmdSave) em um common dialog.

No form copie-e-cole este código:

Private Sub cmdOpen_Click()
Form1.CommonDialog1.Filter = "Texto Simples (*.txt) |*.txt|"
Form1.CommonDialog1.FilterIndex = 1
Form1.CommonDialog1.Action = 1
Filename = Form1.CommonDialog1.Filename
OpenFile (Filename)
End Sub

Private Sub cmdSave_Click()
Form1.CommonDialog1.Filter = "Texto Simples (*.txt) |*.txt|"
Form1.CommonDialog1.FilterIndex = 1
Form1.CommonDialog1.Action = 2
Filename = Form1.CommonDialog1.Filename
CloseFile (Filename)
End Sub

//Em seguida crie um modulo e copie-e-cole isso:

Dim ArrayNum As Integer
Global Filename As String
Const MB_YESNO = 4, MB_ICONQUESTION = 32, IDNO = 7, MB_DEFBUTTON2 = 256


Sub OpenFile(Filename As String)
On Error GoTo uhoh
Dim F As Integer
       F = FreeFile
        Open Filename For Input As F
        Form1!Text1.Text = Input$(LOF(F), F)
        Close F
        Exit Sub
       
uhoh:
Exit Sub
End Sub

Sub DoUnLoadPreCheck(unloadmode As Integer)
If unloadmode = 0 Or unloadmode = 3 Then
  Unload Form1
End If
End Sub

Sub CloseFile(Filename As String)
Dim F As Integer
On Error GoTo CloseError
'   If Dir(Filename) <> "" Then
'      response = MsgBox("Já existe um arquivo de mesmo nome, deseja sobrescrevê-lo?", MB_YESNO + MB_QUESTION + MB_DEFBUTTON2, "Erro")
'      If response = IDNO Then Exit Sub
'   End If
  F = FreeFile
  Open Filename For Output As F
  Print #F, Form1!Text1.Text
  Close F
  Filename = " Sem Título"
  Exit Sub

CloseError:
  MsgBox "Ocorreu um erro durante salvamento do arquivo, refaça a operação.", 48, "Erro"
  Exit Sub
End Sub