VB.NET-在for each*.doc循环期间打开文档时创建异常
好的,我正在做一个小工具,它基本上擦除指定文件夹中每个.*doc文件的文档属性。代码正在工作,但是,如果文档已经打开,我会看到一个文本框,询问我是否要打开只读副本等。如果出现这种情况,我希望代码中止,而是将其写在日志文件或其他文件中。然后转到下一个文件。我该怎么做?我说的是编辑成千上万的文档 这是我目前掌握的代码: 导入Office=Microsoft.Office.Core 导入Word=Microsoft.Office.Interop.Word 导入System.IOVB.NET-在for each*.doc循环期间打开文档时创建异常,vb.net,exception-handling,properties,Vb.net,Exception Handling,Properties,好的,我正在做一个小工具,它基本上擦除指定文件夹中每个.*doc文件的文档属性。代码正在工作,但是,如果文档已经打开,我会看到一个文本框,询问我是否要打开只读副本等。如果出现这种情况,我希望代码中止,而是将其写在日志文件或其他文件中。然后转到下一个文件。我该怎么做?我说的是编辑成千上万的文档 这是我目前掌握的代码: 导入Office=Microsoft.Office.Core 导入Word=Microsoft.Office.Interop.Word 导入System.IO Public Clas
Public Class Form1
Dim oWord As Word.Application
Dim oDoc As Word.Document
Dim oBuiltInProps As Object
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
oWord = CreateObject("Word.Application")
oWord.Visible = False
End Sub
Public Sub findDocLoop()
Dim strRootPath As String
strRootPath = txtBoxRootpath.Text
Dim di As New IO.DirectoryInfo(strRootPath)
Dim aryFi As IO.FileInfo() = di.GetFiles("*.doc")
Dim fi As IO.FileInfo
For Each fi In aryFi
RunRenameProcess(txtBoxRootpath.Text & "\" & fi.ToString)
Next
End Sub
Private Sub RunRenameProcess(ByVal strFile)
'Create instance of Word and make it visible
oDoc = oWord.Documents.Open(strFile)
'Get the properties collection in file
oBuiltInProps = oDoc.BuiltInDocumentProperties
'Set the value of the properties
oBuiltInProps.Item("Company").Value = "Nothing"
oDoc.Save()
oDoc.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
findDocLoop()
End Sub
修复了这个小功能:
Public Function FileInUse(ByVal sFile As String) As Boolean
Dim thisFileInUse As Boolean = False
If System.IO.File.Exists(sFile) Then
Try
Using f As New IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
thisFileInUse = False
End Using
Catch
thisFileInUse = True
writeToLog(sFile)
End Try
End If
Return thisFileInUse
End Function