My.Computer.FileSystem.DeleteDirectory () with read-only files?

I recently ran into a problem with My.Computer.FileSystem.DeleteDirectory(). It will not delete read-only files.

I found on Google that I can delete read-only files by changing the file attributes to "Normal". Therefore, I wrote a recursive function as shown below.

Private Sub DeleteDir(ByVal dir As DirectoryInfo)

    For Each d In dir.GetDirectories
        DeleteDir(d)
    Next
    For Each f In dir.GetFiles
        Try
            f.Attributes = FileAttributes.Normal
            f.Delete()
        Catch ex As Exception
            Log(ex.Message)
        End Try
    Next
    dir.Delete(True)
End Sub

Everything seems to be fine, but it would be nice if there My.Computer.FileSystem.DeleteDirectory()was another option for deleting read-only files or there was an easier way to do this.

+3
source share
2 answers

, My (, VB6), .Net . My , , , . , , , .

, , , , , .

Btw, , dir.Delete(True) .

+1

, . . , , . , , .

Imports System
Imports System.IO
Imports System.Runtime.CompilerServices
Imports System.Linq

Public Module DirectoryExtensions

    <Extension()>
    Public Sub Delete(directory As DirectoryInfo, 
                      recursive As Boolean, 
                      forceReadOnlyDelete As Boolean
    )
        directory.ForceDelete()
    End Sub

    <Extension()>
    Public Sub ForceDelete(ByVal directory As DirectoryInfo)

        directory.RemoveReadOnlyAttributeFromFiles(True)
        directory.Delete(True)

    End Sub

    <Extension()>
    Public Sub RemoveReadOnlyAttributeFromFiles(ByVal directory As DirectoryInfo, ByVal recursive As Boolean)

        Dim readOnlyFiles = From f In directory.GetFiles()
            Where (f.Attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly

        For Each file In readOnlyFiles
            file.Attributes = FileAttributes.Normal
        Next

        If recursive Then

            For Each subDirectory In directory.GetDirectories()
                subDirectory.RemoveReadOnlyAttributeFromFiles(True)
            Next

        End If

    End Sub

End Module
+2

Source: https://habr.com/ru/post/1766133/


All Articles