【问题标题】:vb.net for each loop counter每个循环计数器的 vb.net
【发布时间】:2015-08-16 23:14:12
【问题描述】:

我正在尝试制作一个程序来组织充满随机内容的文件夹。我希望它将每种文件类型放入一个描述其中内容的文件夹中。我在另一个数组中有文件类型数组,所以它可以循环。

它可以很好地移动数组中指定的文件类型,但是当我试图让它把每种类型放到一个单独的文件夹中时,它说数组索引超出了范围。

如果您将名称的索引替换为数字,它可以正常工作,但我无法让它自动更改它。

这是我正在使用的代码:

Dim Extensions As Array = {Audio, Video, Image, Document, PlainText, Batch, Powershell, VB, DiskImage, Compressed, Excutable, Model, Code, Web, Registry}
Dim Names As String() = {"Audio", "Videos", "Pictures", "Documents", "Text Documents", "Batch", "Powershell", "Visual Basic", "DiskImages", "Compressed Files", "Excutables", "3d Models", "Code", "Web", "Registry"}

    Dim number As Integer = 0
    For Each type As String() In Extensions
        number += 1
        path = path + Names(number)

        For Each extension As String In type
            Label2.Text = extension
            CopyMove(FolderBrowserDialog2.SelectedPath, path, extension, s)
        Next

    Next

【问题讨论】:

  • 您应该增加number 作为循环中的last 动作,而不是第一个动作。数组是零索引的,所以Names(0) 是列表中的第一项,而不是Names(1)
  • 或者:将数字初始化为 -1 而不是 0。

标签: arrays vb.net foreach


【解决方案1】:

像这样的配对数组是不好的做法。创建一个类然后使用该类的单个数组或列表要好得多:

Public Class FileType
    Public Property Category As String   
    Public Property Extensions As List(Of String)
End Class

Dim Filetypes As New List(Of FileType) From {
    New FileType() With {Category = "Audio", Extensions = Audio },
    New FileType() With {Cateogry = "Video", Extensions = Video }
    '...
} 


For Each type As FileType In FileTypes
    Dim thisPath As String = Path.Combine(path, type.Category)

    For Each extension As String In type.Extensions
        Label2.Text = extension ' this label won't update inside the method, but that's another question
        CopyMove(FolderBrowserDialog2.SelectedPath, thisPath, extension, s)
    Next
Next

【讨论】:

    【解决方案2】:

    您主要有三个问题:

    1. 数组是从零开始的,因此在循环结束之前不应将 1 添加到数字迭代器,否则音频将进入“视频”,视频将进入“图片”,最终注册表将溢出输出路径.
    2. 在 VB 中,you should use ampersand "&" when concatenating strings
    MsgBox(4 + 5)  ' output: 9
    MsgBox(4 & 5)  ' output: 45
    
    1. 这些配对数组实际上只是“键值对”,.Net 中有一个特定的类称为字典,您应该在这里使用它:

    字典基本上就像一个数组(它是一个“集合”),而不是将数字作为键,您可以输入您选择的自定义变量类型(如字符串!),所以不要尝试要找到与文件扩展名匹配的扩展名,在数组中查找,然后将其与另一个数组进行比较,您只需说“给我扩展名的文件夹路径('.txt')”,它就会完成所有配对为你工作。

    带字典的示例程序:

    在您的表单上创建一个“TextBox”,默认命名为“TextBox1”。

    找到属性“MultiLine”并将其设置为 true。

    让它变大。

    源代码:

    Public Class Form1
    
        ' List of file types that I want to sort
        Private fileFolders As New Dictionary(Of String, String) From {
            {".txt", "documents"},
            {".doc", "documents"},
            {".docx", "documents"},
            {".png", "images"},
            {".jpg", "images"},
            {".mp4", "videos"}
        }   ' TODO: Add more
    
        Private Sub MoveFiles(Optional sourceDirectory As String = "")
    
            TextBox1.Text = ""
    
            If sourceDirectory = "" Then sourceDirectory = "source"
            ' list of files to sort
            Dim files As String() = IO.Directory.GetFiles(sourceDirectory, "*.txt", IO.SearchOption.AllDirectories)
    
            If files.Length = 0 Then
                TextBox1.Text &= "No files were found in source directory!"
                Exit Sub
            End If
    
            Dim fileName As String
            Dim fileExtension As String
            Dim folderName As String
            For Each sourceFile As String In files
                fileName = IO.Path.GetFileName(sourceFile)
                fileExtension = IO.Path.GetExtension(sourceFile)
    
                ' set folderName to "misc" if I don't have an extension case in my dictionary to handle it:
                If fileFolders.ContainsKey(fileExtension) Then
                    folderName = fileFolders(fileExtension) ' dictionary entry gets used here
                Else
                    folderName = "misc"
                End If
    
                CheckCreateDirectory(folderName) ' creates folder if doesn't exist
                ' String interpolation is prettier than string concatenation and highly optimized, feel free to use it a lot,
                ' the syntax is dollar sign, opening quotes, literal string, insert variables in braces, closing quotes:
                TextBox1.Text &= $"Moving file: [{sourceFile}] to folder: [{folderName}]{Environment.NewLine}"
                IO.File.Move(sourceFile, fileFolders(folderName) & "\" & fileName)
            Next
        End Sub
    
        Private Sub CheckCreateDirectory(directoryName As String)
            If Not IO.Directory.Exists(directoryName) Then
                TextBox1.Text &= $"Folder: [{directoryName}] does not exist, creating folder" & vbCrLf
                IO.Directory.CreateDirectory(directoryName)
            End If
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            MoveFiles("source")
        End Sub
    End Class
    
    

    在您的编译/输出目录中创建一个名为“source”的文件夹以对其进行测试并添加一两个文件:

    运行程序:

    应该已经创建了目录并且应该已经对文件进行了排序:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 2011-11-26
      • 1970-01-01
      相关资源
      最近更新 更多