如何判断某个 Excel 文件是否使用 VB.NET 打开? [英] How to tell if a certain Excel file is open using VB.NET?
问题描述
我正在将我的数据集导出到 Excel 文件,并且我想确保我控制了所有文件错误.我特别担心的一个问题是访问一个已经打开的文件.发生一般的 IOException 表示进程无法访问文件 'C:\Reports\report300.csv',因为它正被另一个进程使用."这是将发生错误的行:
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)
我想我可以在它周围抛出一个try catch,但是如果发生与此特定事件无关的IOException怎么办?有没有办法在允许此代码运行之前检查文件是否已打开?我在谷歌上搜索,但找不到直接的答案,尤其是当我使用 excel 时.
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.
提前致谢.
推荐答案
您可以使用 Marshal.GetLastWin32Error() 找出导致异常的 Windows 错误.例如:
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
这篇关于如何判断某个 Excel 文件是否使用 VB.NET 打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!