开发者

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

开发者 https://www.devze.com 2023-01-01 17:36 出处:网络
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

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.Str开发者_Go百科eamWriter(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
0

精彩评论

暂无评论...
验证码 换一张
取 消