4

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 ?

Bpk7
  • 89
  • 1
  • 1
  • 5

2 Answers2

6
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
qwr
  • 3,660
  • 17
  • 29
  • @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 – qwr Jan 30 '14 at 12:17
0
Dim FileLic As New System.IO.StreamWriter("Licenseaccepted", False)

        '("Licenseaccepted", False)
        FileLic.WriteLine(lblLICaccept.Text)
        FileLic.WriteLine(AuthorYear)
        FileLic.WriteLine("Non cancellare o modificare questo file.")
        FileLic.Close()

This solution worked correctly for me.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
LucianoB
  • 1
  • 2