2011-05-27 130 views
0

好吧,我正在做一个小工具,基本上擦除指定文件夹中每个.doc文件的文档属性。然而,如果文档已经打开,代码正在工作,我会看到一个文本框,询问我是否想打开一个只读副本等。如果发生这种情况,我希望代码中止,而不是写下来日志文件什么的。然后转到下一个文件。我怎样才能做到这一点?我正在谈论编辑数千个文件。VB.NET - 为每个* .doc循环打开文档时创建异常

这是我的代码至今:

进口处= Microsoft.Office.Core 进口字=的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 

回答

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