none
delete temporary files from word RRS feed

  • Question

  • I'm trying to change the properties of a word programmatically. 
    To do this I created a windows service from. Net.

    I have this code 

     Sub ModificarPropiedadesWord()
            Dim filePaths As String()
            filePaths = Directory.GetFiles("C:\Words\")
            If filePaths.Length > 0 Then
                For Each fi As String In filePaths
                    If Wapp Is Nothing Then
                        Wapp = New Word.Application
                    End If
                    If docWord Is Nothing Then
                        docWord = New Word.Document
                    Else
                    End If
                    Dim info As New FileInfo(fi)
                    Try
                        docWord = Wapp.Documents.Open("C:\Words\" + Path.GetFileNameWithoutExtension(info.Name) + ".doc")
                        Dim _BuiltInProperties As Object = docWord.BuiltInDocumentProperties
                        If Not _BuiltInProperties Is Nothing Then
                            _BuiltInProperties("Author").Value = "TEST"
                            _BuiltInProperties("Subject").Value = "TEST"
                            _BuiltInProperties("Manager").Value = "TEST"
                            _BuiltInProperties("Company").Value = "TEST"
                            _BuiltInProperties("Category").Value = "TEST"
                            _BuiltInProperties("Keywords").Value = "TEST"
                            _BuiltInProperties("Comments").Value = ""TEST"
                            docWord.Saved = False
                            docWord.Save()
                        End If
                        If Not docWord Is Nothing Then
                            docWord.Close()
                            docWord = Nothing
                        End If
                        If Not Wapp Is Nothing Then
                            Wapp.Quit()
                            Wapp = Nothing
                        End If
                    Catch ex As Exception
                        Dim w As New IO.StreamWriter("C:\logDAL.txt", True)
                        w.WriteLine("ExcepTion modify properties" & ex.ToString() & "  " & DateAndTime.Now.ToString())
                        w.Close()
                    End Try
                Next
            End If
        End Sub

    works well while the service runs continuously, but errors if interrupted.

    I get the classic error 
    "The process can not access the file is being because is used by another process"

    because in the process keeps running background also generates temporary files and others like show in the image

    sow mi question is , how i can handled this bugs=???

    Wednesday, April 2, 2014 5:09 PM

Answers

  • Hi,

    According to your description, I think your issue is not related to running interrupted or continuously. I suspect there may be some temporary Word documents in your folders currently. When you open the temporary document with a new Word application in the code, it will throw an exception. But you haven’t close the document when catching an exception. So when you open the document next time, it will throw the error above. So I suggest you closing the Word document when catching exception.

    In addition, if you want to delete the temporary documents, you could resort to FileInfo.Delete() method.

    By the way, if the no other Word document need to be opened before running the code, you could consider adding code to kill all other Word process to make sure no Word document has been using at the start of the code.

    Sub ModificarPropiedadesWord()
        Dim filePaths As String()
        Dim Wapp As Word.Application
        Dim docWord As Word.Document
        KillWordProgress()
        filePaths = Directory.GetFiles("C:\Users\WordFolder\")
        
        If filePaths.Length > 0 Then
            If Wapp Is Nothing Then
                Wapp = New Word.Application
            End If
            For Each fi As String In filePaths
                If docWord Is Nothing Then
                    docWord = New Word.Document
                Else
                End If
                Dim info As New FileInfo(fi)
                Try
                    docWord = Wapp.Documents.Open("C:\Users\WordFolder\" + Path.GetFileNameWithoutExtension(info.Name) + ".docx")
                    Dim _BuiltInProperties As Object = docWord.BuiltInDocumentProperties
                   If Not _BuiltInProperties Is Nothing Then
                        _BuiltInProperties("Author").Value = "TEST"
                        _BuiltInProperties("Subject").Value = "TEST"
                        _BuiltInProperties("Manager").Value = "TEST"
                        _BuiltInProperties("Company").Value = "TEST"
                        _BuiltInProperties("Category").Value = "TEST"
                        _BuiltInProperties("Keywords").Value = "TEST"
                        _BuiltInProperties("Comments").Value = "TEST"
                        docWord.Saved = False
                        docWord.Save()
                    End If
                Catch ex As Exception
                    Dim w As New IO.StreamWriter("C:\logDAL.txt", True)
                    w.WriteLine("ExcepTion modify properties" & ex.ToString() & "  " & DateAndTime.Now.ToString())
                    w.Close()
                    info.Delete()
                Finally
                    If Not docWord Is Nothing Then
                        docWord.Close()
                        docWord = Nothing
                    End If
                End Try 
            Next
            If Not Wapp Is Nothing Then
                Wapp.Quit()
                Wapp = Nothing
            End If
        End If
    End Sub
    
    Sub KillWordProgress()
        Dim pro As Process
        For Each pro In Process.GetProcessesByName("winword")
            pro.Kill()
        Next
    End Sub




    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, April 3, 2014 9:57 AM
    Moderator
  • Hi,

    I think you don't need to delete all temporary documents with a specific function. Since when running the first code you provided, it will catch an exception when opening a temporary document, if you close the document and application at this time, it won't affect the other document to be edited. If you refer to the code I post in my first reply, you will find I delete the exception documents, so after running the code, the temporary documents will be deleted.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, April 4, 2014 1:17 AM
    Moderator

All replies

  • Hello,

    You can kill Word like that:

          // Get all running winword processes		  
          List<int> processIds = new List<int>();
          foreach (Process process in Process.GetProcessesByName("winword"))
          {
            processIds.Add(process.Id);
          }
    
    		  Application wordApplication = new Application();
    	
            foreach (Process process in Process.GetProcessesByName("winword"))
            {
              if (!process.HasExited && !processIds.Contains(process.Id))
              {
                process.Kill();
              }
            }
    -----------------------------------------
     if the reply help you mark it as your answer.
     Free Managed .NET ExcelWordPDF Component(Create, Modify, Convert & Print)

    Thursday, April 3, 2014 1:09 AM
  • hi Noodles LV. 
    I'm already trying to do that, but does not delete temporary, at least not the first time I run it, do not know why. What am I doing wrong.?
     Protected Overrides Sub OnStart(ByVal args() As String)
            ' System.Diagnostics.Debugger.Launch()
            Dim w As New IO.StreamWriter("C:\logDAL.txt", True)
            w.WriteLine("<<<<<<Se inició el servicio a las " & "   " & DateAndTime.Now + " " + ">>>>>>")
            w.Close()
            Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("winword")
            For Each p As Process In pProcess
                p.Kill()
            Next
            Try
                If (Directory.Exists("C:\Words\")) Then
                    Dim filePaths As String()
                    filePaths = Directory.GetFiles("C:\Words\")
                    For Each fi As String In filePaths
                        File.Delete(fi)
                    Next
                    Directory.Delete("C:\Words\")
                End If
            Catch ex As Exception
                Dim w1 As New IO.StreamWriter("C:\logDAL.txt", True)
                w1.WriteLine(ex.ToString + "  " + DateAndTime.Now)
                w1.Close()
            End Try
            Directory.CreateDirectory("C:\Words\")
            temporizador = New Timers.Timer
            With temporizador
                .Interval = 60000
                .Start()
            End With
            ' Agregue el código aquí para iniciar el servicio. Este método debería poner
            ' en movimiento los elementos para que el servicio pueda funcionar.
        End Sub
    another question, why are you doing this, and did you use it? 
       WordApplication Application = new Application (); 
    and also is this, process.HasExited?
    Thursday, April 3, 2014 2:24 AM
  • You really shouldn't be trying to create a Word instance for each iteration of the loop. Try something along the lines of:

    Sub ModificarPropiedadesWord()
        Dim filePaths As String()
        filePaths = Directory.GetFiles("C:\Words\")
        If filePaths.Length > 0 Then
            If Wapp Is Nothing Then
                Wapp = New Word.Application
            End If
            For Each fi As String In filePaths
                Dim info As New FileInfo(fi)
                Try
                    docWord = Wapp.Documents.Open("C:\Words\" + Path.GetFileNameWithoutExtension(info.Name) + ".doc")
                    Dim _BuiltInProperties As Object = docWord.BuiltInDocumentProperties
                    If Not _BuiltInProperties Is Nothing Then
                        _BuiltInProperties("Author").Value = "TEST"
                        _BuiltInProperties("Subject").Value = "TEST"
                        _BuiltInProperties("Manager").Value = "TEST"
                        _BuiltInProperties("Company").Value = "TEST"
                        _BuiltInProperties("Category").Value = "TEST"
                        _BuiltInProperties("Keywords").Value = "TEST"
                        _BuiltInProperties("Comments").Value = ""TEST"
                        docWord.Save()
                        docWord.Close()
                        docWord = Nothing
                    End If
                Catch ex As Exception
                    Dim w As New IO.StreamWriter("C:\logDAL.txt", True)
                    w.WriteLine ("ExcepTion modify properties" & ex.ToString() & "  " & DateAndTime.Now.ToString())
                    w.Close()
                End Try
            Next
            If Not Wapp Is Nothing Then
                Wapp.Quit()
                Wapp = Nothing
            End If
        End If
    End Sub


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Thursday, April 3, 2014 2:51 AM
  • hi macropod

    thanks for your answer. 
    I can not test the code now, but are you sure it works? 
    because I do not see when you create the instance of docWord, is not necessary: new docWord? 
    also 
    this line has brought me problems 
      docWord.Close (), not with the code I posted now. 
    but before if something like "rpc server unavailable"

    • Edited by Augusto C Thursday, April 3, 2014 3:11 AM
    Thursday, April 3, 2014 3:07 AM
  • With the code I posted the new 'docWord' document is created with:
    docWord = Wapp.Documents.Open("C:\Words\" + Path.GetFileNameWithoutExtension(info.Name) + ".doc")

    With your code, these lines:
                    If docWord Is Nothing Then
                        docWord
    = New Word.Document
                   
    Else
                   
    End If
    simply create yet another document. So, for every document you process with your code you're opening two documents but only closing one.


    Cheers
    Paul Edstein
    [MS MVP - Word]


    • Edited by macropodMVP Thursday, April 3, 2014 3:50 AM
    Thursday, April 3, 2014 3:49 AM
  • Hi,

    According to your description, I think your issue is not related to running interrupted or continuously. I suspect there may be some temporary Word documents in your folders currently. When you open the temporary document with a new Word application in the code, it will throw an exception. But you haven’t close the document when catching an exception. So when you open the document next time, it will throw the error above. So I suggest you closing the Word document when catching exception.

    In addition, if you want to delete the temporary documents, you could resort to FileInfo.Delete() method.

    By the way, if the no other Word document need to be opened before running the code, you could consider adding code to kill all other Word process to make sure no Word document has been using at the start of the code.

    Sub ModificarPropiedadesWord()
        Dim filePaths As String()
        Dim Wapp As Word.Application
        Dim docWord As Word.Document
        KillWordProgress()
        filePaths = Directory.GetFiles("C:\Users\WordFolder\")
        
        If filePaths.Length > 0 Then
            If Wapp Is Nothing Then
                Wapp = New Word.Application
            End If
            For Each fi As String In filePaths
                If docWord Is Nothing Then
                    docWord = New Word.Document
                Else
                End If
                Dim info As New FileInfo(fi)
                Try
                    docWord = Wapp.Documents.Open("C:\Users\WordFolder\" + Path.GetFileNameWithoutExtension(info.Name) + ".docx")
                    Dim _BuiltInProperties As Object = docWord.BuiltInDocumentProperties
                   If Not _BuiltInProperties Is Nothing Then
                        _BuiltInProperties("Author").Value = "TEST"
                        _BuiltInProperties("Subject").Value = "TEST"
                        _BuiltInProperties("Manager").Value = "TEST"
                        _BuiltInProperties("Company").Value = "TEST"
                        _BuiltInProperties("Category").Value = "TEST"
                        _BuiltInProperties("Keywords").Value = "TEST"
                        _BuiltInProperties("Comments").Value = "TEST"
                        docWord.Saved = False
                        docWord.Save()
                    End If
                Catch ex As Exception
                    Dim w As New IO.StreamWriter("C:\logDAL.txt", True)
                    w.WriteLine("ExcepTion modify properties" & ex.ToString() & "  " & DateAndTime.Now.ToString())
                    w.Close()
                    info.Delete()
                Finally
                    If Not docWord Is Nothing Then
                        docWord.Close()
                        docWord = Nothing
                    End If
                End Try 
            Next
            If Not Wapp Is Nothing Then
                Wapp.Quit()
                Wapp = Nothing
            End If
        End If
    End Sub
    
    Sub KillWordProgress()
        Dim pro As Process
        For Each pro In Process.GetProcessesByName("winword")
            pro.Kill()
        Next
    End Sub




    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, April 3, 2014 9:57 AM
    Moderator
  • hi macropod ,

    since i put your code i get this exception

    Exception changing properties: System.Runtime.InteropServices.COMException (0x8001010A): The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))

    Thursday, April 3, 2014 2:36 PM
  • I don't know what might be causing that error. Have you tried the code posted by Luna Zhang?

    Cheers
    Paul Edstein
    [MS MVP - Word]

    Thursday, April 3, 2014 9:50 PM
  •  Private WithEvents temporizador As System.Timers.Timer
        Private docWord As Word.Document
        Private Wapp As Word.Application
        Protected Overrides Sub OnStart(ByVal args() As String)
            ' System.Diagnostics.Debugger.Launch()
            Dim w As New IO.StreamWriter("C:\logDAL.txt", True)
            w.WriteLine("<<<<<<Se inició el servicio a las " & "   " & DateAndTime.Now + " " + ">>>>>>")
            w.Close()
            Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("winword")
            For Each p As Process In pProcess
                p.Kill()
            Next
            Try
                If (Directory.Exists("C:\Words\")) Then
                    Dim filePaths As String()
                    filePaths = Directory.GetFiles("C:\Words\")
                    For Each fi As String In filePaths
                        File.Delete(fi)
                    Next
                    Directory.Delete("C:\Words\")
                End If
            Catch ex As Exception
                Dim w1 As New IO.StreamWriter("C:\logDAL.txt", True)
                w1.WriteLine(ex.ToString + "  " + DateAndTime.Now)
                w1.Close()
            End Try
            Directory.CreateDirectory("C:\Words\")
            temporizador = New Timers.Timer
            With temporizador
                .Interval = 60000
                .Start()
            End With
         

            ' Agregue el código aquí para iniciar el servicio. Este método debería poner
            ' en movimiento los elementos para que el servicio pueda funcionar.
        End Sub

        Protected Overrides Sub OnStop()
            ' Agregue el código aquí para realizar cualquier anulación necesaria para detener el servicio.
            Dim w As New IO.StreamWriter("C:\logDAL.txt", True)
            w.WriteLine("Se paró el servicio    " + Now.ToString)
            w.Close()
        End Sub
        Sub CargarWordEnCarpeta()
            Dim objActualizaWord As New ActualizaWord
            Dim listadeWords As New List(Of ArchivoWord)
            listadeWords = objActualizaWord.RecuperarWord
            If listadeWords.Count > 0 Then
                For Each elemento As ArchivoWord In listadeWords
                    'File.WriteAllBytes("D:\ActualizaWordService\ActualizaWordService\Words\" + elemento.idArchivo.ToString() + ".doc", elemento.contenidoArchivos)
                    File.WriteAllBytes("C:\Words\" + elemento.idArchivo.ToString() + ".doc", elemento.contenidoArchivos)
                Next
            End If
        End Sub
        Sub ModificarPropiedadesWord()
            KillWordProgress()
            Dim filePaths As String()
            filePaths = Directory.GetFiles("C:\Words\")
            If filePaths.Length > 0 Then
                For Each fi As String In filePaths
                    If Wapp Is Nothing Then
                        Wapp = New Word.Application
                    End If
                    'If docWord Is Nothing Then
                    '    docWord = New Word.Document
                    'Else
                    'End If
                    Dim info As New FileInfo(fi)
                    Try
                        docWord = Wapp.Documents.Open("C:\Words\" + Path.GetFileNameWithoutExtension(info.Name) + ".doc")
                        Dim _BuiltInProperties As Object = docWord.BuiltInDocumentProperties
                        If Not _BuiltInProperties Is Nothing Then
                            _BuiltInProperties("Author").Value = "JNE"
                            '_BuiltInProperties("Subject").Value = "RESOLUCION"
                            '_BuiltInProperties("Manager").Value = "JNE_PRUEBA"
                            '_BuiltInProperties("Company").Value = "JNE_PRUEBA"
                            '_BuiltInProperties("Category").Value = "JNE_PRUEBA"
                            '_BuiltInProperties("Keywords").Value = "JNE_PRUEBA"
                            '_BuiltInProperties("Comments").Value = "JNE_PRUEBA"
                            docWord.Saved = False
                            docWord.Save()
                        End If
                        If Not docWord Is Nothing Then
                            docWord.Close()
                            docWord = Nothing
                        End If
                        If Not Wapp Is Nothing Then
                            Wapp.Quit()
                            Wapp = Nothing
                        End If
                    Catch ex As Exception
                        Dim w As New IO.StreamWriter("C:\logDAL.txt", True)
                        w.WriteLine("Excepcion modificando propiedades: " & ex.ToString() & "  " & DateAndTime.Now.ToString())
                        w.Close()
                        ' info.Delete()
                    End Try
                Next
            End If
        End Sub
        Sub ActualizaWordEnBaseDeDatos()
            Dim filePaths As String()
            filePaths = Directory.GetFiles("C:\Words\")
            For Each fi As String In filePaths
                Dim info As New FileInfo(fi)
                Dim file1() As Byte = File.ReadAllBytes(fi)
                Dim archivo As New ArchivoWord
                archivo.idArchivo = Convert.ToInt32(Path.GetFileNameWithoutExtension(info.Name))
                archivo.contenidoArchivos = file1
                Dim objAcualizaWordenBD As New ActualizaWord
                objAcualizaWordenBD.ActualizaWord(archivo)
                File.Delete(fi)
            Next
        End Sub
        Private Sub temporizador_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles temporizador.Elapsed
            Dim w As New IO.StreamWriter("C:\logDAL.txt", True)
            w.WriteLine("Aqui despues de 60 segundos    " + Now.ToString)
            w.Close()
            Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("winword")
            For Each p As Process In pProcess
                p.Kill()
            Next
            CargarWordEnCarpeta()
            ModificarPropiedadesWord()
            ActualizaWordEnBaseDeDatos()
        End Sub
        Sub KillWordProgress()
            Dim pro As Process
            For Each pro In Process.GetProcessesByName("winword")
                pro.Kill()
            Next
        End Sub
    End Class
    Thursday, April 3, 2014 11:21 PM
  • this error is not repeat any more

    Exception changing properties: System.Runtime.InteropServices.COMException (0x8001010A): The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))

    Occasionally, and without knowing why, I get

    Exception changing properties: System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) 
        in Microsoft.Office.Interop.Word._Application.get_Documents () 
        in ActualizaWordService.Service1.ModifyWordProperties () 03/04/2014 4:42:19 pm

    in my log of errors and does not change anything.

    please help!!, in another post someone told me than there is not a god thing automate with officce

    then i think than maybe is because is not so good to do so.

    http://social.msdn.microsoft.com/Forums/office/en-US/d311895a-04cc-4b33-baae-b2fef3e69722/words-reference-dll?forum=worddev#b4a809eb-becf-4528-bef4-99643da2a908

    Thursday, April 3, 2014 11:27 PM
  • Hi,

    I think you don't need to delete all temporary documents with a specific function. Since when running the first code you provided, it will catch an exception when opening a temporary document, if you close the document and application at this time, it won't affect the other document to be edited. If you refer to the code I post in my first reply, you will find I delete the exception documents, so after running the code, the temporary documents will be deleted.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, April 4, 2014 1:17 AM
    Moderator