VB - Writing to a file with StreamWriter

20,360
Dim write As  IO.StreamWriter 
Try 
  write=New IO.StreamWriter(file)  
  write.write(txtEncryption.text)

Catch ex As Exception
  'Prompt error
  Console.WriteLine("Error {0}",ex.Message)

Finally 
    If write IsNot Nothing Then
        write.Close() 
    End If
End Try 

Assumption (if file was not opened anywhere else) : You open already opened one.Make sure that all your opened streams closed properly. You can use this syntax too

Using writer As StreamWriter = New StreamWriter(file)
        writer.Write("....")
           //and so on
End Using
Share:
20,360
Bpk7
Author by

Bpk7

Updated on January 31, 2020

Comments

  • Bpk7
    Bpk7 over 4 years

    I'm trying to write to a file using the StreamWriter.

    Dim write as IO.StreamWriter
    write = new io.streamwriter(file)
    write.write(txtEncryption.text)
    write.close
    

    I stopped the code in debug mode and i saw it crashes and goes straight to the exception when reaches line 2.

    It is because i just made the file and it's still in use ? How can i avoid that ?

  • qwr
    qwr over 10 years
    @user3246386 I posted code that will handle error. Probably you open file but without closing you try to open again. So use using to handle close per open properly