Remove directory and it's contents (files, subdirectories) without using FileSystemObject

℡╲_俬逩灬. 提交于 2019-12-17 20:47:12

问题


I want to know if it's possible to rewrite this piece of code:

Private Sub PrepareDir(ByVal dir As String)
    Dim fso As New FileSystemObject
    If fso.FolderExists(dir) Then Call fso.DeleteFolder(dir, True)
    Call fso.CreateFolder(dir)
End Sub

With VBA statements: Kill, MkDir, etc. Most "difficult" part of this - remove non-empty directory. With FSO it can be done easily, but how it can be done without FSO?


回答1:


This piece of ccode uses RmDir to remove the Folder. AFAIK, RmDir cannot delete the folder unless it is empty, so we first clear the content in the folder then remove the directory.

Private Sub PrepareDirModified(dirStr As String)
On Error Resume Next
    If Right(dirStr, 1) <> "\" Then dirStr = dirStr & "\"
    Kill dirStr & "*.*" 
    RmDir dirStr
    MkDir dirStr
On Error GoTo 0
End Sub

Hope this helps.




回答2:


The OP said they want to rewrite their code "without FSO" but it doesn't make sense.

If the goal is to reduce the amount of code, simply make it a one-liner:

CreateObject("Scripting.FileSystemObject").DeleteFolder "x:\myFolder"

As requested, this permanently removes the folder and it's contents.


More Information:

  • Microsoft Docs : DeleteFolder Method
  • Ron de Bruin : Delete files and folders


来源:https://stackoverflow.com/questions/25401789/remove-directory-and-its-contents-files-subdirectories-without-using-filesys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!