开发者

how do I put contents of C: into an array?

Am learning arrays at the moment and I have the below piece of code that goes through drive C: and displays the files in in a list box.

I want to try and expand it to use array.sort so that it gets the files, puts them into an array, and then I can sort by filename or file size. I have been rattling my brain over this - as to how do I put the files into an array.

Would like an 开发者_运维技巧explanation if possible as more interested in learning it rather than the answer.

Thanks!

Private Sub btnclick_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclick.Click

    Call Clearlist()

    Dim strFilesinfo As System.IO.FileInfo
    Dim strlength As Double = 0
    Dim strname As String = ""

    For Each strFiles As String In My.Computer.FileSystem.GetFiles("c:\")

        strFilesinfo = My.Computer.FileSystem.GetFileInfo(strFiles)

        strlength = strFilesinfo.Length
        strname = strFilesinfo.Name

        lstData.Items.Add(strname & " " & strlength.ToString("N0"))


    Next
End Sub
End Class


To allow the data to be sortable, you'd need to be displaying something that could treat that information separately (i.e. a class or structure). You might also find that a different type of control, such as a DataGridView might be easier to get to grips with.

The .Net framework does define an interface, IBindingList which collections can implement to show that they report, amongst other things, sorting.


I'm providing this as a sample for learning purposes but it should not be used as-is. Getting every file from the entire C:\ should not be done like this. Aside from the performance issues there are windows security limitations that won't actually let you do this.

The FileList being populated here is getting just the TopDirectoryOnly. If you change that input to "AllDirectories" it will get all the subdirectories but it will fail as I stated before.

    Dim path As String = "C:\"
    Dim dir As New System.IO.DirectoryInfo(path)

    Dim fileList = dir.GetFiles("*.*", IO.SearchOption.TopDirectoryOnly)

    Dim fileSort = (From file In fileList _
                    Order By file.Name _
                    Select file.Name, file.Length).ToList

    For Each file In fileSort
        With file
            lstData.Items.Add(String.Format("{0} {1}", .Name, .Length.ToString("N0")))
        End With
    Next file

Just change the Order By in the LINQ query to change how the sorting is done. There are many other ways to do the sorting but LINQ will handle it for you with very little code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜