每个循环计数器的vb.net

时间:2015-08-16 23:14:13

标签: arrays vb.net foreach

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

它可以移动数组中指定的文件类型,但是当我尝试将每个类型放入一个单独的文件夹时,它表示数组索引超出范围。

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

以下是我正在使用的代码:

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

2 个答案:

答案 0 :(得分:3)

这样的配对阵列是不好的做法。创建一个类然后使用该类的单个数组或List更好:

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

答案 1 :(得分:0)

您主要有三个问题:

  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”的文件夹以对其进行测试并添加一两个文件:

enter image description here

运行程序:

enter image description here

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

enter image description here