简体   繁体   中英

How to tell if a certain Excel file is open using VB.NET?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM