If My.Computer.FileSystem.DirectoryExists(“C:\CreaCartella") = False Then 'controlla se la cartella esiste
My.Computer.FileSystem.CreateDirectory("C:\CreaCartella")
Else
MsgBox("Questa cartella è già esistente")
End If
Imports System.IO
Public Class Form1
'Lista le cartelle (solo la prima serie di subcartelle) e aggiunge gli Attributi
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim n As Integer
Dim Item As ListViewItem
Dim dir As New DirectoryInfo("c:\")
Try
For Each subDir As DirectoryInfo In dir.GetDirectories
n += 1
Dim aggiunta() As String = {subDir.Name, subDir.Attributes.ToString}
Item = New ListViewItem(aggiunta)
ListView1.Items.Add(Item)
Next
Catch ex As Exception
End Try
Label1.Text = n
End Sub
End Class
Imports System.IO
Public Class Form1
Dim totFile As Integer
Dim totDir As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FbD.ShowNewFolderButton = False ' Tolgo il Button aggiungi Cartella
FbD.ShowDialog()
If (FbD.SelectedPath IsNot Nothing) Then
Label1.Text = FbD.SelectedPath
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If Label1.Text = "" Then
MsgBox("Scegliere una cartella!")
Return
End If
totDir = 0
totFile = 0
TextBox1.Text = ""
TextBox2.Text = ""
ElencoDir(Label1.Text)
'TextBox2.Text = FilePath
End Sub
Function ElencoDir(ByVal Dir As String)
Try
Dim subdir As String() = Directory.GetDirectories(Dir)
For Each subdirectory As String In subdir
ElencoDir(subdirectory)
TextBox1.AppendText(subdirectory & vbCrLf)
totDir += 1
Next
Dim listaFile As String() = Directory.GetFiles(Dir)
For Each fileName As String In listaFile
ElencoDir(fileName)
TextBox2.AppendText(fileName & vbCrLf)
totFile += 1
Next
Catch ex As Exception
End Try
Label4.Text = totDir
Label5.Text = totFile
End Function
End Class
IImports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim n As Integer
Dim Item As ListViewItem
Dim dir As New DirectoryInfo("c:\")
Try
For Each subDir As DirectoryInfo In dir.GetDirectories
n += 1
Dim aggiunta() As String = {subDir.Name, subDir.Attributes.ToString}
Item = New ListViewItem(aggiunta)
ListView1.Items.Add(Item)
Try
For Each subdir2 As DirectoryInfo In subDir.GetDirectories
n += 1
Dim aggiunta2() As String = {" " & subdir2.Name, subdir2.Attributes.ToString}
Item = New ListViewItem(aggiunta2)
ListView1.Items.Add(Item)
Try
For Each subdir3 As DirectoryInfo In subdir2.GetDirectories
n += 1
Dim aggiunta3() As String = {" " & subdir3.Name, subdir3.Attributes.ToString}
Item = New ListViewItem(aggiunta3)
ListView1.Items.Add(Item)
Next
Catch ex As Exception
End Try
Next
Catch ex As Exception
End Try
Next
Catch ex As Exception
End Try
Label1.Text = n
End Sub
End Class
B1. Creare una nuova cartella
B1. Create a new folder
Namespace : Imports System.IO:
Dim cartella As String = "c:\CreaCartella"
My.Computer.FileSystem.CreateDirectory(cartella)
Se il percorso non è valido il sistema genera l’eccezione “DirectoryNotFound”. Se la cartella esiste non
viene comunque generata un’eccezione
Per sapere se la cartella esiste già:
Oppure:
If Not Directory.Exists("c:/CreaCartella") Then
Directory.CreateDirectory("c:/CreaCartella")
End If
Se vogliamo modificare l’attributo della cartella e dei file contenuti:
Dim cartella As String = "c:\CreaCartella"
My.Computer.FileSystem.CreateDirectory(cartella)
Dim attributi As New DirectoryInfo("c:\CreaCartella")
attributi.Attributes = attributi.Attributes.Hidden
Questo è l’esempio proposto da Microsoft (creazione e cancellazione della cartella):
If
the
path
is
not
valid,
the
system
generates
the
"DirectoryNotFound"
exception.
If
the
folder
exists,
an
exception is not generated
To find out if the folder already exists
Namespace used:
Imports System.IO
B2. OpenFileDialog
2. OpenFileDialog
OpenFileDialog è una delle preziose finestre di dialogo che VB Net mette a disposizione. Ecco alcuni
esempi di come usarla.
Creare un nuovo progetto con un Form, cinque Button, una Label e un TextBox. Dalla Casella Strumenti
selezionare OpenFileDialog.
Cliccare due volte su Button1 e inserire le seguenti righe:
Dim ofd As OpenFileDialog = New OpenFileDialog()
If ofd.ShowDialog = System.Windows.Forms.DialogResult.OK Then
Label1.Text = ofd.FileName ‘il percorso completo del file viene scritto nella Label1
End If
Lo stesso risultato lo ottengo con (Button2):
Dim ofd As OpenFileDialog = New OpenFileDialog()
Dim result As DialogResult = ofd.ShowDialog()
If result = DialogResult.OK Then
Dim path As String = ofd.FileName
Label1.Text = path
End If
‘Per scegliere una cartella (per esempio Documenti) con cui aprire OpenFileDialog (Button3):
Per filtrare i file in base ad una estensione (Button4):
Avviare un’applicazione e aprire il file scelto con OpenFileDialog
'Se è un file .txt legge il contenuto e lo trasferisce nel TextBox
'Se non è .txt avvia l'applicazione e apre il file
TextBox1.Text = ""
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim percorso As String = OpenFileDialog1.FileName
Dim est As String = percorso.Substring(percorso.Length - 3) 'tipo estensione = ultime 3 lettere del percorso
If est = "txt" Then 'se è un file .txt lo legge e scrive nel textBox
TextBox1.AppendText(File.ReadAllText(OpenFileDialog1.FileName))
Return
End If
Process.Start(percorso) 'avvia l'applicazione e apre il file
End If
B3. Elenca in un ListView le subcartelle di una cartella aggiungendo Attributes
3. List in a ListView the
Directory subfolders
OpenFileDialog
is
one
of
the
pre-
defined
dialogs
that
VB
Net
makes
available.
Here
are
some
examples
of how to use it.
Create
a
new
project
with
a
Form,
as
follow.
Double
click
on
Button1
and
insert
the following lines:
To
choose
a
folder
(for
example
Documents) to open OpenFileDialog
To filter files based on the extension
Launch
an
application
to
open
the
file chosen with OpenFileDialog
Creare un progetto con un Form, due etichette, un Button e un ListView. Inserire il seguente codice
Per eseguire una ricerca sequenziale di tutte le subcartelle si aggiungono tanti cicli “For Each …
Next” quante sequenze di subcartelle si vogliono scannerizzare. Nell’esempio che segue ne
aggiungo solo tre:
Or
If we want to change the Attribute:
Microsoft
suggestion
to
create
or
delete directories:
To
perform
a
sequential
search
of
all
sub-folders,
add
as
many
cycles
"For
Each
...
Next"
as
you
want
to
scan
the
sub-folders.
In
the
following
example I add only three cycles.
B4. Lista Cartelle e lista file utilizzando una funzione
Con una funzione e poche righe di codice possiamo ottenere un elenco di tutte le subcartelle e dei
file contenuti. Rispetto alla versione vista sopra l’elaborazione richiede più tempo.
B5. Lista cartelle in un DataGridView
In questo esempio le cartelle e le subcartelle vengono elencate in un DataGridView. I DGV
permettono un disposizione molto flessibile e pulita dei dati e la loro riutilizzazione risulta facilmente
gestibile. Si possono introdurre tanti cicli “For Each …. Next” per ottenere i dati di quante gerarchie
di cartelle si desideri.
Imports System.IO
Public Class Form1
'Aprire Visual Studio come Amministratore
Public n As Integer
'Elenca solo direttori singole senza sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dir As New DirectoryInfo(Label3.Text)
Try
For Each subDir As DirectoryInfo In dir.GetDirectories
DataGridView1.Rows.Add(subDir.Name, subDir.FullName, subDir.Attributes.ToString)
n = n + 1
Next
Catch unatho As UnauthorizedAccessException
Catch ex As Exception
End Try
Label1.Text = n
End Sub
'Elenca tutte le cartelle anche quelle particolari(Hidde, System etc)
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dir As New IO.DirectoryInfo(Label3.Text)
Cursor = Cursors.WaitCursor
Try
For Each subDir As DirectoryInfo In dir.GetDirectories
DataGridView1.Rows.Add(subDir.Name, subDir.FullName, subDir.Attributes.ToString)
n = n + 1
Try
For Each subDir2 As DirectoryInfo In subDir.GetDirectories
DataGridView1.Rows.Add(subDir2.Name, subDir2.FullName, subDir2.Attributes.ToString)
n = n + 1
Try
For Each subDir3 As DirectoryInfo In subDir2.GetDirectories
DataGridView1.Rows.Add(subDir3.Name, subDir3.FullName, subDir3.Attributes.ToString)
n = n + 1
Next
Catch ex As Exception
End Try
Next
Catch ex As Exception
End Try
Next
Catch unatho As UnauthorizedAccessException
MsgBox("Dir inaccessbile")
Catch ex As Exception
End Try
Cursor = Cursors.Arrow
Label1.Text = n
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
FolderBrowserDialog1.ShowNewFolderButton = False ' Tolgo il Button aggiungi Cartella
FolderBrowserDialog1.ShowDialog()
If (FolderBrowserDialog1.SelectedPath IsNot Nothing) Then
Label3.Text = FolderBrowserDialog1.SelectedPath
End If
End Sub
End Class
4. List Directories and files
using a function
5. List Directories In a
DataGridView
In
this
example,
folders
and
subfolders
are
listed
in
a
DataGridView.
The
DGVs
allow
a
very
flexible
and
clean
disposition
of
the
data,
moreover
their
re-use
is
easily
manageable.
You
can
introduce
many
cycles
"For
Each
....
Next
"to
get
the
data
of
how
many
hierarchies of folders you want.
With
a
function
and
a
few
lines
of
code
we
can
get
a
list
of
all
sub-
folders
and
files.
Compared
to
the
version
seen
above
(and
down
B5),
processing takes longer.
B6. Lista cartelle e file (metodo EnumerateFiles) in RichTextBox
Rispetto all’esempio precedente B5 questa versione ha un’esecuzione molto più lenta. Per contro il
codice, se utilizzato per gerarchie di cartelle molto lunghe, è decisamente semplificato. Nell’elenco
File, fra due cartelle diverse viene interposta una linea vuota.
Imports System.IO
Public Class Form1
Dim n, nDir As Integer 'Numero file e nr cartelle
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FolderBrowserDialog1.ShowNewFolderButton = False ' Tolgo il Button aggiungi Cartella
FolderBrowserDialog1.ShowDialog()
If (FolderBrowserDialog1.SelectedPath IsNot Nothing) Then
Label2.Text = FolderBrowserDialog1.SelectedPath
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Dirpath As String = Label2.Text
Dim NonFiles = SalvaEnumeratore.EnumerateFiles(Dirpath, "*.*", SearchOption.AllDirectories)
Dim nomeDir As String
For Each strFil In NonFiles
RichTextBox1.AppendText(strFil & " " & Chr(10))
nDir += 1
Next
Dim lines As New List(Of String) 'Legge le righe del richtextbox1 (ogni riga una cartella)
lines.AddRange(RichTextBox1.Lines)
n = 1
Dim dire As New DirectoryInfo(Dirpath)
For Each finfo As FileInfo In dire.GetFiles
RichTextBox2.AppendText(n & " " & finfo.FullName & " " & finfo.Attributes.ToString & Chr(10))
n += 1
Next
RichTextBox2.AppendText(" " & Chr(10))
For lnr = 0 To lines.Count - 2 Step 1
nomeDir = RichTextBox1.Lines(lnr)
Dim dir As New DirectoryInfo(nomeDir)
Try
For Each finfo As FileInfo In dir.GetFiles()
RichTextBox2.AppendText(n & " " & finfo.FullName & " " & finfo.Attributes.ToString & Chr(10))
n = n + 1
Next
RichTextBox2.AppendText(" " & Chr(10))
Catch ex As Exception
End Try
Next
Label1.Text = (n)
Label4.Text = nDir
End Sub
Friend Class SalvaEnumeratore
Public Shared Function EnumerateFiles(strPath As String, strFileSpec As String, soOptions As SearchOption) As
IEnumerable(Of String)
Try
Dim DirEnum = Enumerable.Empty(Of String)()
If soOptions = SearchOption.AllDirectories Then
DirEnum = Directory.EnumerateDirectories(strPath).SelectMany(Function(x) EnumerateFiles(x,
strFileSpec, soOptions))
End If
Return DirEnum.Concat(Directory.EnumerateDirectories(strPath, strFileSpec,
SearchOption.TopDirectoryOnly)) 'fornisce la dir senza il file
Catch ex As UnauthorizedAccessException
Return Enumerable.Empty(Of String)()
End Try
End Function
End Class
End Class
Gestione cartelle - Folder management
Dim ofd As OpenFileDialog = New OpenFileDialog()
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If ofd.ShowDialog = System.Windows.Forms.DialogResult.OK Then
Label1.Text = ofd.FileName
End If
Dim ofd As OpenFileDialog = New OpenFileDialog()
ofd.Title = "TROVA FILE WORD"
ofd.Filter = "Word Documents|*.docx"
ofd.ShowDialog()
Per filtrare i file in base a più estensioni (Button5):
Dim ofd As OpenFileDialog = New OpenFileDialog()
ofd.Title = "TROVA FILE DI TESTO"
ofd.Filter = "File di Testo|*.docx;*.txt;*.rtf;*.pdf"
ofd.ShowDialog()
Compared to the previous example
B5 this version has a much slower
execution. On the other hand, the
code, if used for very long directory
hierarchies, is definitely simplified. In
the File list, an empty line is placed
between two different folders.
Folders
Backup
è
un’efficiente
applicazione
per
il
salvataggio
di
cartelle
o
intere
partizioni.
Offre
quanto
serve
per
garantire
una
corretta
gestione
dei
backup
con
una
notevole
semplicità
d’uso
e
un’interfaccia
che
permette
un’impostazione
alla
portata
dei
meno
esperti
e
che
fornisce
subito
tutte
le
informazioni
necessarie
per
avere
una
chiara visione dello stato dei propri backups.
Folders
Backup
is
an
efficient
application
for saving folders or entire partitions.
It
offers
what
you
need
to
ensure
proper
backup
management
with
a
remarkable
ease
of
use
and
an
interface
that
allows
a
setting
within
the
reach
of
the
less
experienced
and
that
immediately
provides
all
the
information
you
need
to
have
a
clear
view of the status of your backups.
Invia Email
S
end Email
' Specify the directories you want to manipulate.
Dim path As String = "c:\MyDir"
Try
' Determine whether the directory exists.
If Directory.Exists(path) Then
MsgBox("That path exists already.")
Return
End If
' Try to create the directory.
Dim di As DirectoryInfo = Directory.CreateDirectory(path)
MsgBox("The directory was created successfully")
' Delete the directory.
di.Delete()
MsgBox("The directory was deleted successfully")
Catch ex As Exception
MsgBox("The process failed")
End Try
B7. Elencare i file “.txt” di una cartella e leggerne il contenuto
Inserire nel Form1 1 Button, 1 Label, 1 ListBox e un RichTextBox.
B7. List the ".txt" files in a
folder and read their contents
Insert in Form1 1 Button, 1 Label, 1
ListBox and a RichTextBox.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
FolderBrowserDialog1.ShowDialog()
Dim cartella As String = FolderBrowserDialog1.SelectedPath
Label1.Text = cartella
Dim Docu() As String = Directory.GetFiles(cartella)
Dim percorso As String
Dim estensione As String
For Each percorso In Docu
estensione = Path.GetExtension(percorso).ToLower
If estensione = ".txt" Then
ListBox1.Items.Add(percorso)
End If
Next
End Sub
Private Sub ListBox1_Click(sender As Object, e As System.EventArgs) Handles ListBox1.Click
Dim read As System.IO.StreamReader
RichTextBox1.Clear()
read = File.OpenText(ListBox1.SelectedItem)
While read.Peek <> -1
RichTextBox1.Text = RichTextBox1.Text + read.ReadLine()
End While
End Sub
End Class