2010-11-05 6 views
6

Supponendo che ho una struttura di cartelle come:DirectoryInfo.Delete (True) Non Elimina quando la struttura cartella è aperta in Esplora risorse

C:\MyTemp 
    - MySubFolder

Se provo a cancellare questo utilizzando:

Dim path As String = "C:\MyTemp" 
Dim di As System.IO.DirectoryInfo 
di = System.IO.Directory.CreateDirectory(path) 
di.CreateSubdirectory("MySubFolder") 
di.Delete(True) 

Funziona correttamente, a meno che non sia aperto Windows Explorer e sto guardando la directory "MySubFolder". Poi ottengo una IOException La directory non è vuota. - fare clic su OK e questo non viene eliminato.

Qualche idea su come posso eseguire correttamente questa operazione (ad esempio eliminare), anche quando si esegue questo codice mentre si apre la cartella aperta in Esplora risorse?

+4

Si noti che questo è il comportamento standard della shell. Otterrete lo stesso messaggio di errore da 'rmdir/S'. Immagino che la cancellazione non funzioni perché Explorer ha ancora un handle per la sottocartella aperta. –

+0

@ 0xA3 - Non è coerente. Vedi il mio commento sulla risposta qui sotto. Ci sono casi in cui posso eliminare una cartella mentre la guardo in Windows Explorer e quindi Explorer solo navs nella cartella padre del figlio che è stata cancellata. –

+0

@ToddMain So che questo è vecchio ma apprezzerò davvero se è possibile pubblicare la soluzione per questo. –

risposta

1

Dai un'occhiata a questo article. IOException può essere generato da un handle aperto alla directory: This open handle can result from enumerating directories and files che è esattamente ciò che apre in explorer. Sembra che il vero messaggio di errore sia generico.

+0

sì, l'avevo letto, ma afferma che si applica solo a WinXP e prima.in secondo luogo, assumo sotto una cartella * MySub * Ho un'altra sottocartella chiamata "Temp" e un file in essa chiamato "mypic.jpg". Se guardo la cartella "Temp" in Windows Explorer ed elimini (e il jpg) usando il codice sopra, esso cancella. È stato incoerente e non sono sicuro di cosa fare al riguardo. –

2

unico modo per ottenere questo "lavorare" al 100% è costantemente dal bombardamento nucleare Explorer (cattiva idea) o bombardare la maniglia (also bad idea)

Il mio consiglio sarebbe quello di gestire solo il fallimento con grazia al contrario di cercare Questo.

1

Il meglio che puoi fare è prendere l'errore e quindi utilizzare handle.exe per scoprire quale processo sta utilizzando il file e chiedere all'utente di chiudere l'applicazione con le opzioni per tentativi o annullare.

Vi siete mai chiesti su quale programma sono aperti determinati file o directory? Ora puoi scoprirlo. Handle è un'utilità che visualizza le informazioni sugli handle aperti per qualsiasi processo nel sistema. Puoi usarlo per vedere i programmi che hanno un file aperto, o per vedere i tipi di oggetto ei nomi di tutti gli handle di un programma.

Alcuni maggiori informazioni qui:

How to monitor process' IO activity using C#?

0

mi si avvicinò con il seguente metodo di estensione DirectoryInfo che avvolge il metodo DirectoryInfo.Delete nativo() e tenta di "tranquillamente cancellare" nella cartella specificata:

Questo metodo richiede il seguente riferimento COM: Microsoft Internet Controls COM Reference: Microsoft Internet Controls x


    '''' <summary> 
    '''' Attempts to perform a "Safe delete" by searching for any Windows File Explorer instances attached to the extended DirectoryInfo Object 
    '''' and navigate those instances off the current DirectoryInfo path in an attempt to prevent a "Directory is not empty" IOException when 
    '''' calling DirectoryInfo.Delete(recursive). 
    '''' </summary> 
    '''' <param name="DirectoryInfo">The DirectoryInfo object being extended</param> 
    '''' <param name="recursive">Optional: true to delete this directory, its subdirectories, and all files; otherwise false</param> 
    '''' <returns>A Boolean indicating whether the DirectoryInfo.Delete(recursive) operation completed without an Exception</returns> 
    '''' <remarks>Authored by CMC 2013-05-06 12:04:25 PM</remarks> 
    <System.Runtime.CompilerServices.Extension()> _ 
    Public Function TrySafeDelete(ByVal [DirectoryInfo] As DirectoryInfo, Optional ByVal recursive As Boolean = False, Optional ByVal retryCount As Integer = 0) As Boolean 
     Const maxRetryCount As Integer = 10 
     retryCount = If(retryCount < 0, 0, retryCount) 
     Dim success As Boolean = True 
     If ([DirectoryInfo] IsNot Nothing) Then 
      [DirectoryInfo].Refresh() 
      Dim msWinShellIExplorerWindowsLockingCurrentDirectory As Dictionary(Of SHDocVw.InternetExplorer, DirectoryInfo) = New Dictionary(Of SHDocVw.InternetExplorer, DirectoryInfo) 
      If ([DirectoryInfo].Exists()) Then 
       Try 
        Dim msWinShellIExplorerWindows As SHDocVw.ShellWindows = New SHDocVw.ShellWindows() 
        For Each msWinShellIExplorerWindow As SHDocVw.InternetExplorer In msWinShellIExplorerWindows 
         If (msWinShellIExplorerWindow.Name.Equals("windows explorer", StringComparison.OrdinalIgnoreCase)) Then 
          Dim locationValue As String = msWinShellIExplorerWindow.LocationURL() 
          If (locationValue.Length() > 0) Then 
           Dim locationURI As Uri = Nothing 
           If (Uri.TryCreate(locationValue, UriKind.RelativeOrAbsolute, locationURI)) Then 
            Dim msWinShellDirectoryInfo As DirectoryInfo = New DirectoryInfo(locationURI.LocalPath()) 
            Dim isLockingCurrentDirectory As Boolean = msWinShellDirectoryInfo.FullName.ToLower().Contains([DirectoryInfo].FullName.ToLower()) 
            If (isLockingCurrentDirectory AndAlso Not msWinShellIExplorerWindowsLockingCurrentDirectory.ContainsKey(msWinShellIExplorerWindow)) Then msWinShellIExplorerWindowsLockingCurrentDirectory.Add(msWinShellIExplorerWindow, msWinShellDirectoryInfo) 
           End If 
          End If 
         End If 
        Next 

        Dim navigateCompleteCount As Integer = 0 
        If (msWinShellIExplorerWindowsLockingCurrentDirectory.Any()) Then 
         For Each msWinShellDirectoryEntry As KeyValuePair(Of SHDocVw.InternetExplorer, DirectoryInfo) In msWinShellIExplorerWindowsLockingCurrentDirectory 
          Dim msWinShellIExplorerWindow As SHDocVw.InternetExplorer = msWinShellDirectoryEntry.Key() 
          Dim msWinShellDirectoryInfo As DirectoryInfo = msWinShellDirectoryEntry.Value() 
          AddHandler msWinShellIExplorerWindow.NavigateComplete2, New SHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler(Sub(pDisp As Object, ByRef URL As Object) 
                                        navigateCompleteCount += 1 
                                        If (navigateCompleteCount.Equals(msWinShellIExplorerWindowsLockingCurrentDirectory.Count())) Then 
                                         With [DirectoryInfo] 
                                          .Delete(recursive) 
                                          .Refresh() 
                                         End With 
                                        End If 
                                       End Sub) 
          msWinShellIExplorerWindow.Navigate2(New Uri(msWinShellDirectoryInfo.Root.FullName()).AbsoluteUri()) 
         Next 
        Else 
         With [DirectoryInfo] 
          .Delete(recursive) 
          .Refresh() 
         End With 
        End If 
       Catch ex As Exception 
       End Try 

       [DirectoryInfo].Refresh() 
       If ([DirectoryInfo].Exists() AndAlso (retryCount <= maxRetryCount)) Then 
        [DirectoryInfo].TrySafeDelete(recursive, retryCount + 1) 
       End If 
       success = Not DirectoryInfo.Exists() 
      End If 
     End If 
     Return success 
    End Function 
Problemi correlati