VB.NET - 在每个* .doc循环期间打开文档时创建异常

时间:2011-05-27 07:33:16

标签: vb.net exception-handling properties

好的,所以我正在做一个小工具,它基本上擦除了指定文件夹中每个。* doc文件的文档属性。代码正在运行,但是,如果文档已经打开,我会看到一个文本框,询问我是否要打开只读副本等。我希望代码在发生时中止,而是将其写入日志文件或其他东西。然后转到下一个文件。我怎样才能做到这一点?我正在谈论编辑成千上万的文件。

这是我到目前为止的代码:

Imports Office = 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

1 个答案:

答案 0 :(得分:0)

使用这个小功能修正了它:)

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