views:

29

answers:

1

I'm exporting my Dataset to an excel file, and I want to make sure I keep any file errors under control. One in particular that I'm concerned about is accessing a file that's already open. A general IOException occurs that says "The process cannot access the file 'C:\Reports\report300.csv' because it is being used by another process." Here is the line in which the error will occur:

Dim output As New IO.StreamWriter(path, False, UnicodeEncoding.Default)

I guess I could just throw a try catch around it, but what if an IOException happens that isnt related to this particular incident? Is there a way I can check to see if the file is already open before allowing this code to run? I looked on google but couldn't find a straight answer, especially when I'm using excel.

Thanks in advance.

+1  A: 

You can use Marshal.GetLastWin32Error() to find out what Windows error caused the exception. For example:

Public Shared Function OpenUnlockedFile(ByVal path As String) As StreamWriter
    Dim sw As StreamWriter = nothing
    Try
        sw = New StreamWriter(path)
    Catch ex As IOException When System.Runtime.InteropServices.Marshal.GetLastWin32Error() = 32
        REM locked, return nothing
    End Try
    Return sw
End Function
Hans Passant
Nice! I didn't think it would be that easy. Many thanks!
broke