【发布时间】:2012-12-18 14:14:06
【问题描述】:
我使用File.Exists(filePath) 检查文件是否存在。然后我尝试使用Excel.Workbooks.OpenText(filePath) 在 Excel 中打开文件。但 Excel 抱怨该文件不存在。什么鬼?
上下文是我正在使用另一个应用程序来处理给定文件并生成一个 .out 文件,然后我将其转换为 Excel 工作簿。
'' At this point, filePath is a .txt file.
Dim args As String = String.Format("""{0}""", filePath)
...
Dim exe As String = Config.ExtractEXE
Dim i As New ProcessStartInfo(exe)
i.Arguments = args
Dim p As Process = Process.Start(i)
p.WaitForExit()
...
'' filePath now becomes the .out file.
'' Then eventually, I get around to checking:
'If Not File.Exists(filePath) Then
' MsgBox("Please ensure...")
' Exit Sub
'End If
'' In response to an answer, I no longer check for the existence of the file, but
'' instead try to open the file.
Private Function fileIsReady(filePath As String) As Boolean
Try
Using fs As FileStream = File.OpenRead(filePath)
Return True
End Using
Catch
Return False
End Try
End Function
Do Until fileIsReady(filePath)
'' Wait.
Loop
ExcelFile.Convert(filePath...)
'' Wherein I make the call to:
Excel.Workbooks.OpenText(filePath...)
'' Which fails because filePath can't be found.
是否存在延迟问题,例如 .Net 在其他应用程序可以访问文件之前识别文件的存在?我只是不明白为什么File.Exists() 可以告诉我文件在那里,然后 Excel 找不到它。
据我所知,唯一可能打开文件的应用程序是我调用来进行处理的应用程序。但是该应用程序应该在 p.WaitForExit() 完成时完成文件,对吧?
我不得不将此应用程序作为一个已知错误来部署,这真的很糟糕。用户有一个简单的解决方法;但仍然 - 这个错误不应该。希望你能帮忙。
【问题讨论】:
-
当时文件是否被其他应用程序打开?例如。独立的 Excel?
-
@Trekstuff,请参阅我在问题中添加的评论以回应您的问题。谢谢!
标签: vb.net excel-2010