使用 vb.net 搜索驱动器 [英] Searching a drive with vb.net

查看:31
本文介绍了使用 vb.net 搜索驱动器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个程序,用于在您的驱动器中搜索可执行文件.

I am making a program that searches your drive for an executable.

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    Dim di As New DirectoryInfo("C:\")
    Dim files() As FileInfo
    Dim a As Integer
    Do While a = 0
        Try
            files = di.GetFiles("FileName.exe", SearchOption.AllDirectories)
        Catch ex As UnauthorizedAccessException
        End Try
        If Not files Is Nothing Then
            a = 1
        End If
    Loop
    txt_Location.Text = files(0).FullName
End Sub

一旦遇到第一个 UnauthorizedAccessException,它就会陷入无限循环.如何跳过产生异常的文件?

As soon as it hits the first UnauthorizedAccessException, it gets stuck in an infinite loop. How do I skip over the files that produce the exception?

这就是我现在所拥有的:

This is what I have now:

Public Sub DirSearch(ByVal sDir As String)
    Dim dir As String
    Try
        For Each dir In Directory.GetDirectories(sDir)
            For Each file In Directory.GetFiles(dir, "Filename.exe")
                ComboBox1.Items.Add(file)
            Next
            DirSearch(dir)
        Next
    Catch ex As Exception
        Debug.WriteLine(ex.Message)
    End Try
End Sub

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
DirSearch("C:\")
End Sub

推荐答案

这里需要递归来处理每个文件夹.

You need recursion here which handles each folder.

根据 OP 的要求,举一个小例子:

As requested by the OP, a little example:

Public Sub DirSearch(ByVal sDir As String)
    Try
        For Each dir as String In Directory.GetDirectories(sDir)
            For Each file In Directory.GetFiles(dir, "yourfilename.exe")
                lstFilesFound.Items.Add(file)
            Next
            DirSearch(dir)
        Next
    Catch ex As Exception
        Debug.WriteLine(ex.Message)
    End Try
End Sub

<小时>

另请看以下答案:


Also take a look at the following answers:

  • Looping through all directory's on the hard drive (VB.NET)
  • How to handle UnauthorizedAccessException when attempting to add files from location without permissions (C#)

另请注意,如果您有足够的访问权限,您可以将代码简化为:

Also note, if you have enough access rights, you could simplify your code to this:

Dim di as New DirectoryInfo()
Dim files = di.GetFiles("iexplore.exe", SearchOption.AllDirectories) 'already returns all files at once

<小时>

最后但并非最不重要的是:

避免无限循环.就像在您的示例中一样,它们可能会导致代码损坏,因为某些情况与您预期的不一样.想象一下,您的代码已在您的 PC 上运行,并且您将此软件部署到了一个客户——可怕的场景中.;-)

Avoid having infinite loops. Like in your example, they can lead to broken code just because some circumstances aren't like you've expected them to be. Imagine your code has run on your PC and you deployed this software to a customer - horrible scenario. ;-)

这篇关于使用 vb.net 搜索驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆