Oppure

Loading
11/10/11 9:14
wuolfit
Salve a tutti,
il mio problema è il seguente : Ho creato un programma di ricerca che funziona egregiamente, difatti una volta impostato il path, puoi trovare il file che ti interessa, digitando il nome o parte di esso, o in alternativa selezionando la data di creazione o modifica, però adesso vorrei poter ricercare i file all'interno del path che gli indico usando * o in alternativa *.* al posto del nome, potreste darmi qualche dritta su come fare????
Grazie infinite per l'aiuto
aaa
11/10/11 9:47
nessuno
Scusa, ma se hai già scritto un programma, come possiamo darti consigli se non ne vediamo il codice?
Ricorda che nessuno è obbligato a risponderti e che nessuno è perfetto ...
---
Il grande studioso italiano Bruno de Finetti ( uno dei padri fondatori del moderno Calcolo delle probabilità ) chiamava il gioco del Lotto Tassa sulla stupidità.
11/10/11 9:50
Nullable
Quoto nessuno; comunque dovresti dirci come il programma controlla quello che immette l'utente. Se questo controllo è effettuato da una if allora basta che tu includa anche il caso in cui l'utente inserisce nella textbox ( per esempio ) il carattere "*" o "*.*", a quel punto ti elenca tutti i files.
aaa
11/10/11 10:02
wuolfit
Tutto il codice del mio programma ve lo riporto di seguito :


Imports System.IO
Imports Microsoft.Win32
Public Class Cerca
#Region "Procedure, funzioni"
    Public Sub SearchFiles(ByVal Dir As String, ByVal SubDir As Boolean)
        Dim Files() As String = Directory.GetFiles(Dir)
        Dim Dirs() As String = Directory.GetDirectories(Dir)
        lblStatus.Text = "Ricerca nella directory " + Dir + " in corso..."
        For Each S As String In Files
            Results.Add(S)
            Application.DoEvents()
        Next
        If SubDir Then
            For Each S As String In Dirs
                SearchFiles(S, True)
                Application.DoEvents()
            Next
        End If
    End Sub
    Public Sub SearchDirectories(ByVal Dir As String)
        Dim Dirs() As String = Directory.GetDirectories(Dir)
        For Each S As String In Dirs
            Directories.Add(S)
            SearchDirectories(S)
        Next
    End Sub
    Public Sub AddFileToList(ByVal FileName As String)
        Dim S(1) As String
        Dim L As ListViewItem
        S(0) = Path.GetFileName(FileName)
        S(1) = FileName
        L = New ListViewItem(S)
        L.Group = lstResult.Groups(0)
        lstResult.Items.Add(L)
    End Sub
    Public Sub AddDirToList(ByVal DirName As String)
        Dim S(1) As String
        Dim L As ListViewItem
        S(0) = GetDirName(DirName)
        S(1) = DirName
        L = New ListViewItem(S)
        L.Group = lstResult.Groups(1)
        lstResult.Items.Add(L)
    End Sub
    Public Sub Transfer(ByRef ArFrom As ArrayList, ByRef ArTo As ArrayList)
        ArTo.Clear()
        For Each S As String In ArFrom
            ArTo.Add(S)
        Next
        ArFrom.Clear()
    End Sub
    Public Function GetDirName(ByVal Dir As String) As String
        Return Dir.Remove(0, Dir.LastIndexOf("\") + 1)
    End Function
    Public Function GetDirLen(ByVal Dir As String) As Double
        Dim Size As Double
        Dim Files() As String = Directory.GetFiles(Dir)
        Dim Dirs() As String = Directory.GetDirectories(Dir)
        For Each S As String In Files
            Size += FileLen(S)
        Next
        For Each S As String In Dirs
            Size += GetDirLen(S)
        Next
        Return Size
    End Function
	Public Function GetIcon(ByVal Ext As String) As Icon
        Dim RegKey As RegistryKey
        Dim KeyName As String
        Dim Icn As Icon
        RegKey = Registry.ClassesRoot.OpenSubKey(Ext)
        KeyName = RegKey.GetValue("(Predefinito)")
        RegKey = Registry.ClassesRoot.OpenSubKey(KeyName).OpenSubKey("DefaultIcon")
        If RegKey Is Nothing Then
            Return Nothing
        End If
        KeyName = RegKey.GetValue("(Predefinito)")
        Icn = Drawing.Icon.ExtractAssociatedIcon(KeyName)
        Return Icn
    End Function
#End Region
    Public Results As New ArrayList
    Public Directories As New ArrayList
    Private Sub chbWord_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chbWord.CheckedChanged
        grpWord.Enabled = chbWord.Checked
    End Sub
	Private Sub cmdBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBrowse.Click
        F.Description = "Selezionare la cartella in cui cercare:"
        If F.ShowDialog = Windows.Forms.DialogResult.OK Then
            txtDir.Text = F.SelectedPath
        End If
    End Sub
    Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click
        If txtDir.Text = Nothing Then
            MsgBox("Nessuna directory inserita: impossibile iniziare la ricerca!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        If chbWord.Checked And txtWord.Text = Nothing Then
            MsgBox("Specificare una parola da cercare nel nome del file!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
		If chbDate.Checked And (cmbField.SelectedIndex < 0 Or cmbWhen.SelectedIndex < 0) Then
            MsgBox("Inserire tutti i campi necessari per condurre una ricerca basata sulla data!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
		Results.Clear()
        lstResult.Items.Clear()
        SearchFiles(txtDir.Text, chbSubDir.Checked)
		Dim Backup As New ArrayList
        Dim W As StreamWriter = Nothing
        If chbWord.Checked Then
            lblStatus.Text = "Selezione dei file che contengano la parola '" + txtWord.Text + "' nel proprio nome in corso..."
            Dim N As String
            For Each S As String In Results
                N = Path.GetFileName(S)
                If chbCase.Checked Then
                    If N.ToLower.Contains(txtWord.Text.ToLower) Then
                        Backup.Add(S)
                    End If
                Else
                    If N.Contains(txtWord.Text) Then
                        Backup.Add(S)
                    End If
                End If
                Application.DoEvents()
            Next
            Transfer(Backup, Results)
            lblStatus.Text = "Selezione delle cartelle che contengano la parola '" + txtWord.Text + "' nel proprio nome in corso..."
            For Each S As String In Directories
                N = GetDirName(S)
                If chbCase.Checked Then
                    If N.ToLower.Contains(txtWord.Text.ToLower) Then
                        Backup.Add(S)
                    End If
                Else
                    If N.Contains(txtWord.Text) Then
                        Backup.Add(S)
                    End If
                End If
                Application.DoEvents()
            Next
            Transfer(Backup, Directories)
        End If
		If chbDate.Checked Then
            lblStatus.Text = "Selezione dei file " + cmbField.SelectedItem + " " + cmbWhen.SelectedItem + " " + mclDate.SelectionRange.Start.ToShortDateString
            Dim F As FileInfo
            Dim P As DirectoryInfo
            Dim D As Date
            Dim Selected As Date = mclDate.SelectionRange.Start
            For Each S As String In Results
                F = New FileInfo(S)
                Select Case cmbField.SelectedIndex
                    Case 0
                        D = F.LastWriteTime
                    Case 1
                        D = F.CreationTime
                    Case 2
                        D = F.LastAccessTime
                End Select
                Select Case cmbWhen.SelectedIndex
                    Case 0
                        If D.CompareTo(Selected) < 0 Then
                            Backup.Add(S)
                        End If
                    Case 1
                        If D.CompareTo(Selected) = 0 Then
                            Backup.Add(S)
                        End If
                    Case 2
                        If D.CompareTo(Selected) > 0 Then
                            Backup.Add(S)
                        End If
                End Select
            Next
            Transfer(Backup, Results)

            lblStatus.Text = "Selezione delle cartelle " + cmbField.SelectedItem + " " + cmbWhen.SelectedItem + " " + mclDate.SelectionRange.Start.ToShortDateString
            For Each S As String In Directories
                P = New DirectoryInfo(S)
                Select Case cmbField.SelectedIndex
                    Case 0
                        D = P.LastWriteTime
                    Case 1
                        D = P.CreationTime
                    Case 2
                        D = P.LastAccessTime
                End Select
                Select Case cmbWhen.SelectedIndex
                    Case 0
                        If D.CompareTo(Selected) < 0 Then
                            Backup.Add(S)
                        End If
                    Case 1
                        If D.CompareTo(Selected) = 0 Then
                            Backup.Add(S)
                        End If
                    Case 2
                        If D.CompareTo(Selected) > 0 Then
                            Backup.Add(S)
                        End If
                End Select
            Next
            Transfer(Backup, Directories)
        End If
		If chbReport.Checked Then
            W = New StreamWriter(Application.StartupPath + "\Report di " + Date.Now.ToLongDateString + ", ore " + Date.Now.ToShortTimeString + ".txt")
        End If
        For Each S As String In Results
            AddFileToList(S)
            If chbReport.Checked Then
                W.WriteLine(S)
            End If
        Next
        For Each S As String In Directories
            AddDirToList(S)
            If chbReport.Checked Then
                W.WriteLine(S)
            End If
        Next
        If chbReport.Checked Then
            W.Close()
        End If
        lblStatus.Text = "Operazione completata: trovati " & Results.Count & " files e " & Directories.Count & " cartelle"
    End Sub
	Private Sub lstResult_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstResult.SelectedIndexChanged
        Try
            Dim Selected As ListViewItem = lstResult.SelectedItems(0)
            If Selected.Group Is lstResult.Groups(0) Then
                Dim F As New FileInfo(Selected.SubItems(1).Text)
                txtInfo.Text = F.Name + vbCrLf + vbCrLf + "Creato il " + F.CreationTime.ToShortDateString + " alle ore " + F.CreationTime.ToShortTimeString + vbCrLf + "Modificato il " + F.LastWriteTime.ToShortDateString + " alle ore " + F.LastWriteTime.ToShortTimeString + vbCrLf + "Aperto l'ultima volta il " + F.LastAccessTime.ToShortDateString + " alle ore " + F.LastAccessTime.ToShortTimeString + vbCrLf + "Grande complessivamente " & F.Length & " bytes (" + RoundSize(F.Length) + ")" + vbCrLf + vbCrLf + "Percorso completo: " + vbCrLf + F.FullName
            Else
                Dim D As New DirectoryInfo(Selected.SubItems(1).Text)
                Dim L As Double = GetDirLen(D.FullName)
                txtInfo.Text = D.Name + vbCrLf + vbCrLf + "Creata il " + D.CreationTime.ToShortDateString + " alle ore " + D.CreationTime.ToShortTimeString + vbCrLf + "Modificata il " + D.LastWriteTime.ToShortDateString + " alle ore " + D.LastWriteTime.ToShortTimeString + vbCrLf + "Aperta l'ultima volta il " + D.LastAccessTime.ToShortDateString + " alle ore " + D.LastAccessTime.ToShortTimeString + vbCrLf + "Grande complessivamente " & L & " bytes (" + RoundSize(L) + ")" + vbCrLf + vbCrLf + "Percorso completo: " + vbCrLf + D.FullName
            End If
        Catch aOoRE As ArgumentOutOfRangeException
        End Try
    End Sub

aaa
11/10/11 11:56
Dedalux
Per fare una ricerca fornendo l'estensione puoi usare la funzione GetFiles della classe directory Directory (Namespace IO)

esempio

IO.Directory.GetFiles(path, "*.mp3")


al posto di *.mp3 puoi inserire * o *.* per cercare tutti i files.

La funzione accetta anche un terzo overload per estendere la ricerca anche a tutto l'albero delle sottodirectory.

Un limite della funzione è che accetta solo un'estensione. Non puoi fare una cosa di questo tipo *.mp3|*.aac|*.jpeg

P.S. Un consiglio. Non ho letto tutto il codice, ma ho notato che concateni molte stringhe con l'operatore +.
Quando le concatenazioni iniziano ad essere numerose, è più performante utilizzare uno StringBuilder (msdn.microsoft.com/it-it/library/…).
aaa
11/10/11 13:59
wuolfit
Grazie Dedalux per il tuo consiglio.......quindi se non ho capito male dovrei trasformare ciò che avevo scritto :

Imports System.IO
Imports Microsoft.Win32
Public Class Cerca
Region "Procedure, funzioni"
Public Sub SearchFiles(ByVal Dir As String, ByVal SubDir As Boolean)
        Dim Files() As String = Directory.GetFiles(Dir)
        Dim Dirs() As String = Directory.GetDirectories(Dir)


in :

Imports System.IO
Imports Microsoft.Win32
Public Class Cerca
Region "Procedure, funzioni"
    Public Sub SearchFiles(ByVal Dir As String, ByVal SubDir As Boolean)
        Dim Files() As String = Directory.GetFiles(Dir, "*")
        Dim Dirs() As String = Directory.GetDirectories(Dir)


Per quanto riguarda lo StringBuilder mi stò documentando.....grazie di nuovo
aaa
12/10/11 13:26
Dedalux
Esatto.

Comunque se quel parametro SubDir ti serve per specificare se la funzione deve cercare anche nelle subdirectories potresti fare una cosa cosi

Dim Files() As String = IO.Directory.GetFiles(Dir, "*", IIf(SubDir, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly))
Ultima modifica effettuata da Dedalux 12/10/11 13:27
aaa
07/11/11 9:40
wuolfit
Grazie mille ho risolto.....gentilissimo....
aaa