【问题标题】:VB.Net - How to Change attributes of Folder included sub folder & filesVB.Net - 如何更改文件夹的属性包括子文件夹和文件
【发布时间】:2016-11-20 13:21:35
【问题描述】:

如何更改或删除所选文件夹的属性,包括所有子文件夹和文件。

我使用了以下代码:

System.IO.SetAttribute(FolderBrowserDialog1.SelectedPath,IO.FileAttribute.Hidden)

但它只更改选定的文件夹属性而不是子文件夹和文件

【问题讨论】:

  • 您需要从用户选择的目录中循环出所有子目录,这是一个递归函数...现在,您只需为所选目录更改它即可。在设置属性之前循环检索每个目录及其文件,然后设置该属性。

标签: vb.net attributes subdirectory


【解决方案1】:

所有子文件夹和文件都可以这样枚举:

If FolderBrowserDialog1.ShowDialog = DialogResult.OK Then

    Dim di = New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
    di.Attributes = di.Attributes Or FileAttributes.Hidden

    For Each i In di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
        i.Attributes = i.Attributes Or FileAttributes.Hidden
    Next
End If

另一种方式可以是attrib.exe

Dim cmd = "attrib +H """ & FolderBrowserDialog1.SelectedPath.TrimEnd("\"c)

Shell("cmd /c " & cmd & """ & " & cmd & "\*"" /S /D", AppWinStyle.Hide)

我希望它比枚举所有文件条目并分别获取和设置每个文件的属性要快,但这种方法的另一个优点是默认情况下,shell 函数不会等待命令完成,您的程序可以无需等待即可继续。

【讨论】:

    【解决方案2】:

    您可以递归地遍历子文件夹。我认为操作系统也是递归的!

    Private Function getAllFolders(ByVal directory As String) As List(of String)
            'Create object
            Dim fi As New IO.DirectoryInfo(directory)
            'Change main folder attribute
            System.IO.SetAttribute(directory,IO.FileAttribute.Hidden )
            'List to store paths
            Dim Folders As New List(Of String)
            'Loop through subfolders
            For Each subfolder As IO.DirectoryInfo In fi.GetDirectories()
                'Add this folders name
    
               Folders.Add(subfolder.FullName)
    
                'Recall function with each subdirectory
                For Each s As String In getAllFolders(subfolder.FullName)
                    Folders.Add(s)
                    'Change subfolders attribute
                    System.IO.SetAttribute(s,IO.FileAttribute.Hidden )
                Next
    
            Next
    
    
            Return Folders
    
     End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 2015-09-14
      • 2018-07-28
      相关资源
      最近更新 更多