【问题标题】:VB.NET - Create exception when document is opened during for each *.doc loopVB.NET - 在每个 *.doc 循环期间打开文档时创建异常
【发布时间】:2011-05-27 07:33:16
【问题描述】:

好的,所以我正在做一个小工具,它基本上可以擦除指定文件夹中每个 .*doc 文件的文档属性。代码正在运行,但是,如果文档已经打开,我会看到一个文本框,询问我是否要打开只读副本等。如果发生这种情况,我希望代码中止,而是将其写下来日志文件什么的。然后继续下一个文件。我怎样才能做到这一点?我说的是编辑数千个文档。

这是我目前的代码:

导入 Office = Microsoft.Office.Core 导入 Word = Microsoft.Office.Interop.Word 导入 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

【问题讨论】:

    标签: vb.net exception-handling properties


    【解决方案1】:

    用这个小功能修复它:)

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多