2011-05-27 50 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