Ok, so I'm doing a small tool that basically wipes the document properties of each .*doc file in a specified folder. The code is working, however, if the document is already opened, I'm presented with a text box asking if I want to open a read only copy etc. I want the code to abort if that happens and rather write it down in a log file or something. And just move on to the next file. How can I do this? I'm talking about editing thousands of documents.
This is the code I have so far:
Imports O开发者_StackOverflowffice = Microsoft.Office.Core Imports Word = Microsoft.Office.Interop.Word Imports System.IO
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
Fixed it with this small function :)
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
精彩评论