File.OpenWrite vs StreamWriter

H

Harry Strybos

I am confused about which is the better (or safer ) way to write files in
VB.Net.

Using sw As StreamWriter = New StreamWriter(fName)
For Each row As DataRow In ds.Tables(0).Rows

For i As Integer = 0 To (ds.Tables(0).Columns.Count - 1)

col = row(i).ToString.Replace(","c, " "c) 'make sure no extra
commas

If (i < (ds.Tables(0).Columns.Count - 1)) Then

sw.Write(col & ",")

Else

sw.Write(col)

End If

Next

sw.WriteLine()

Next

sw.Close()

End Using

seems very simple, but I am told this method leaves a file open if an error
occurs. Is the File.OpenWrite a safer method?

Thank you
 
T

Tom Shelton

I am confused about which is the better (or safer ) way to write files in
VB.Net.

Using sw As StreamWriter = New StreamWriter(fName)
For Each row As DataRow In ds.Tables(0).Rows

For i As Integer = 0 To (ds.Tables(0).Columns.Count - 1)

col = row(i).ToString.Replace(","c, " "c) 'make sure no extra
commas

If (i < (ds.Tables(0).Columns.Count - 1)) Then

sw.Write(col & ",")

Else

sw.Write(col)

End If

Next

sw.WriteLine()

Next

sw.Close()

End Using

seems very simple, but I am told this method leaves a file open if an error

occurs. Is the File.OpenWrite a safer method?

You have been miss informed - when the resource is declared with a
using block, it's dispose method is automatically called as soon as
you exit the block - even if that is via an error condition. In fact,
your sw.Close() is redundant - since the stream will be closed
automatically on the End Using. You can think of Using as being
essentially the same as:

Dim s As New StreamWriter ()
Try
' a bunch of stuff
Finally
s.Close()
End Try
 
D

Derek

Just curious but does the "Using" re-throw the exception afterwards? It
wouldn't be very nice to have my using statements hiding exceptions from the
rest of my code.

i.e.

Try

Catch eX as Exception

Throw

Finally

' Dispose

End Try
 
H

Harry Strybos

Tom Shelton said:
You have been miss informed - when the resource is declared with a
using block, it's dispose method is automatically called as soon as
you exit the block - even if that is via an error condition. In fact,
your sw.Close() is redundant - since the stream will be closed
automatically on the End Using. You can think of Using as being
essentially the same as:

Dim s As New StreamWriter ()
Try
' a bunch of stuff
Finally
s.Close()
End Try

Thanks, guys
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top