1.
Caricare un file .rtf in un RichTextBox e selezionare una linea*
2.
Lettura file .txt con streamer, successiva modifica e salvataggio
3.
Excel : Creare un file e salvarlo*
4.
Excel : Chiudere un file*
5.
Excel : Creare un file in cui salvare i dati di un Array
6.
Leggere un file in esadecimale*
7.
Scaricare un file da un server FTP
8.
Criptare e decriptare un file di testo*
9.
Aprire un file con l’applicazione predefinita
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Directory.Exists("c:/Tempio") = False Then
Directory.CreateDirectory("c:/Tempio")
End If
Using writer As TextWriter = System.IO.File.CreateText("C:\temp\text.txt")
writer.WriteLine("Prova di scrittura")
End Using
End Sub
End Class
.
A1. Creare un file .txt e salvarlo in una cartella
Creare un nuovo progetto con un Form. Cliccare su Form1 per entrare in modo codice e inserire le
seguenti righe di codice
Viene creato il file test.txt nel quale viene scritto un testo. Il File viene salvato nella cartella
C:/Tempo/
NB: Se la cartella non esiste viene creata. Se il file esiste viene aggiornato aggiungendo la riga.
Utilizzando la classe FileStream il file, se esiste, viene sovrascritto:
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Directory.Exists("c:/Tempio") = False Then
Directory.CreateDirectory("c:/Tempio")
End If
Dim lungh As String
Dim fs As FileStream = File.Create("c:\temp\MioTesto.txt")
Dim info As Byte() = New UTF8Encoding(True).GetBytes("Questo è un testo di prova.")
lungh = info.Length
fs.Write(info, 0, lungh)
fs.Close()
End Sub
End Class
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fs As System.IO.StreamWriter
If Directory.Exists("c:/Tempo") = False Then
Directory.CreateDirectory("c:/Tempo")
End If
fs = My.Computer.FileSystem.OpenTextFileWriter("c:/Tempo/test.txt", True)
fs.WriteLine("Testo di prova")
fs.Close()
End Sub
Con l’istruzione Using…End Using:
A2. Cercare file .txt e .rtf e copiarne il testo in una RichTextBox
Mantenendo la formattazione. Creare un nuovo progetto con due Button e un RichTextBox. Inserire
le seguenti righe in Button1(file .txt) e Button2 (file .rtf)
Public Class Form1
Dim openFileDialog1 As New OpenFileDialog()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
RichTextBox1.Text = IO.File.ReadAllText(openFileDialog1.FileName)
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
RichTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.RichText)
End If
End Sub
End Class.
A3. RichTextBox: selezionare una riga, trovare un testo, sostituire un
testo
L’esempio
propone
due
modi
diversi
di
selezionare
un
riga,
due
modi
di
trovare
un
testo
nel
RichTextBox e come sostituire il testo di una riga.
Creare
un
nuovo
progetto
con
un
Form
quattro
Button
e
un
RichTextBox.
Creare
e
memorizzare
un
file
chiamato
test.rtf
con
almeno
6
righe
di
testo.
Oppure
scegliete
un
file
esistente
sostituendo
il
nome nel codice. Inserire il seguente codice:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RichTextBox1.LoadFile("C:\temp\test.rtf", RichTextBoxStreamType.RichText)
End Sub
Public Function SelezionaLinea(ByVal lineNumber As Integer, ByVal richTextBox As RichTextBox)
Dim linea As Integer = 0
For i As Integer = 0 To lineNumber - 1 'Calcola nr caratt. dalla Ia linea fino all'inizio della linea da selezionare
(lineNumber)
linea += richTextBox.Lines(i).Length
linea += 1
Next
Dim length As Integer = richTextBox.Lines(lineNumber).Length 'nr caratteri della linea da selezionare
RichTextBox1.[Select](linea, length) 'seleziona a partire da "linea" un nr di caratteri pari a "lenght"
End Function
'SELEZIONA UNA RIGA - FUNZIONE SelezionaLinea
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Prompt As String
Dim NrLinea As Integer
Me.RichTextBox1.HideSelection = False
Prompt = "inserisci un numero di linea da selezionare"
NrLinea = InputBox(Prompt) - 1 'la linea nr 1 corrisponde alla linea 0 del codice etc
SelezionaLinea(NrLinea, Me.RichTextBox1) 'numero di linea da assegnare alla funzione "SelezionaLinea"
End Sub
'TROVA UN TESTO
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Prompt As String
Dim testo As String
Dim trova As String
Prompt = "inserisci il testo da cercare"
testo = InputBox(Prompt)
trova = RichTextBox1.Find(testo, RichTextBoxFinds.MatchCase)
If trova = -1 Then
MsgBox("testo non trovato")
End If
RichTextBox1.Select()
End Sub
'SELEZIONA UNA RIGA - IndexOf
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Prompt As String
Dim NrLinea As Integer
Prompt = "inserisci un numero di linea da selezionare"
NrLinea = InputBox(Prompt) - 1 'la linea nr 1 = linea 0 dell’array (le linee sono string array del richtextbox!)
'Seleziona la linea NrLinea nel richtextbox (calcolando il nr di caratteri delle linee precedenti) e pone
SelectionStart alla posizione iniziale della linea
RichTextBox1.SelectionStart = RichTextBox1.Text.IndexOf(RichTextBox1.Lines(NrLinea))
'Legge il numero di caratteri della riga selezionata.
RichTextBox1.SelectionLength = RichTextBox1.Lines(NrLinea).Length
'Abbiamo i dati per selezionare correttamente la linea (Start e Nr caratteri)
RichTextBox1.Select()
End Sub
'TROVA TUTTE LE RICORRENZE4 DI UN TESTO
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim SearchText As String
Dim RTBIndex As Integer
SearchText = InputBox("Enter text to be found")
Dim textEnd As Integer = RichTextBox1.TextLength
RTBIndex = 0
Dim lastIndex As Integer = RichTextBox1.Text.LastIndexOf(SearchText)
While RTBIndex < lastIndex
RichTextBox1.Find(SearchText, RTBIndex, textEnd, RichTextBoxFinds.None)
RichTextBox1.SelectionBackColor = Color.Yellow
RTBIndex = RichTextBox1.Text.IndexOf(SearchText, RTBIndex) + 1
End While
End Sub
'SOSTITUISCE IL TESTO DELLA RIGA 4
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
RichTextBox1.Select(RichTextBox1.GetFirstCharIndexFromLine(3), RichTextBox1.Lines(3).Length)
RichTextBox1.SelectedText = “Testo aggiunto alla linea 4"
End Sub
End Class.
Create
a
new
project
with
a
Form
four
Button
and
a
RichTextBox.
Create
and
store
a
file
called
test.rtf
with
at
least
6
lines
of
text.
Or
choose
an
existing
file
by
replacing
the
name
in
the
code.
The
example
offers
two
different
ways
of
selecting
a
line
and
two
ways
of
finding
a
text
in the RichTextBox.
3. RichTextBox: Select a line
and find a text
1. Create a .txt file and save it
in a folder
2. Search for .txt and .rtf files
and copy their text into a
RichTextBox
A4. Lettura file .txt con streamer, modifica e salvataggio
Creare un nuovo progetto con due Button e un TextBox
Imports System.IO
Public Class Form1
Dim percorso As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
'Apre streamreader file selezionato
Dim oggReader As New StreamReader(OpenFileDialog1.FileName)
percorso = OpenFileDialog1.FileName
Dim contenutoFile As String = oggReader.ReadToEnd() 'Legge il contenuto del file
TextBox1.Text = contenutoFile 'e lo inserisce nel TextBox
oggReader.Close()
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim oggWriter As StreamWriter = New StreamWriter(percorso)
'Viene salvato il contenuto del TextBox che quindi può essere modificato
oggWriter.Write(TextBox1.Text)
oggWriter.Close()
End Sub
.
A5. Excel: creare un file, popolarlo con dati e salvarlo
4. Read file .txt with streamer,
change it and save.
5. Excel: create a file, fill it
with data and save
Creiamo un file Excel chiamato “archivio”, inseriamo dati in tre colonne e lo salviamo nella cartella
c:\temp\ (se non esiste viene creata). E’ necessario aggiungere la libreria Microsoft Excel (dal menu
Progetto=> Aggiungi riferimento => Com).
Sono previsti due metodi di chiusura del file Excel (Classe Marshal e Metodo Kill())
We
create
an
Excel
file
called
"archive",
insert
data
in
three
columns
and
save
it
in
the
folder
c:
\
temp
\
(if
it
does
not
exist
it
is
created).
It
is
necessary
to
add
the
Microsoft
Excel
library
(from
the
menu
Project
=>
Add
reference
=>
Com).
Two
methods
of
closing
the
Excel
file
are
described
(Class
Marshal
and Method Kill())
Imports System.Runtime.InteropServices 'Namespace Classe Marshal
Imports Microsoft.Office.Interop 'Namespace Excel applications
Public Class Form1
Public app As Microsoft.Office.Interop.Excel.Application
Public wb As Microsoft.Office.Interop.Excel.Workbook
Public ws As Microsoft.Office.Interop.Excel.Worksheet
Public Nome As String
Public Eta As Integer
Public Data As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
app = New Excel.Application
'Controllo se esiste il file Excel che vogliamo aprire
If (My.Computer.FileSystem.FileExists("c:\temp\archivio.xlsx") = False) Then
'se il file non esiste viene creato
MsgBox("Non esiste un archivio dati. Viene pertanto creato un file Excel in " & vbCr & "
c:\temp\archivio.xlsx")
app = CreateObject("Excel.Application")
End If
wb = app.Workbooks.Add
ws = wb.Worksheets(1)
' Inserisce i titoli delle tre colonne
ws.Range("A1").Value = "Nome"
ws.Range("B1").Value = "Età"
ws.Range("C1").Value = "Data"
'Inserisce alcuni valori
ws.Range("A2").Value = "Paolo"
ws.Range("B2").Value = "40"
ws.Range("C2").Value = Now
wb.SaveAs("c:\temp\archivio.xlsx")
'Se il file esiste viene aperto e letto
wb = app.Workbooks.Open("c:\temp\archivio.xlsx")
ws = app.ActiveSheet
Nome = ws.Cells(2, 1).Value 'Preleva il valore Nome
Eta = ws.Cells(2, 2).Value
Data = ws.Cells(2, 3).Value
Label1.Text = Nome
Label2.Text = Eta
Label3.Text = Data
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Chiude solo il files Excel archivio.xlsx di questa app. non altri files Excel eventualmente aperti (Classe Marshal)
app.Workbooks.Close()
app.Quit()
Marshal.ReleaseComObject(wb)
Marshal.ReleaseComObject(ws)
Marshal.ReleaseComObject(ws)
Marshal.ReleaseComObject(app)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Arresta il processo associato: chiude tutte le istanze Excel aperte
For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
proc.Kill()
Next
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
proc.Kill()
Next
Close()
End Sub
End Class
.
A6. Excel: creare un file in cui salvare i dati di un array
Creare un nuovo progetto. Aggiungi una Label al Form1. Dal Menu Progetto => Aggiungi
Riferimento =>Com aggiungere il riferimento Microsoft Excel. Doppio clic sul Form1 e
inserimento delle seguenti righe di codice:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim excel, wb, ws As Object
Dim Nome(10) As String
Dim Età(10) As Integer
Dim Path As String = ("c:\Temp\Prova.xlsx")
Dim Prompt As String
'Crea un nuovo workbook in Excel
excel = CreateObject("Excel.Application")
wb = excel.Workbooks.Add
'Crea un array con 2 colonne e 10 righe
Dim DataArray(0 To 9, 0 To 1) As Object
Dim i As Integer
'Aggiunge i titoli al worksheet nella riga 1
ws = wb.Worksheets(1)
ws.Range("A1").Value = "Nome"
ws.Range("B1").Value = "Età"
MsgBox("Inserire tre coppie di dati: nome e età")
i = 1
Do Until i = 4 'Crea i dati
Prompt = "inserisci nome"
Nome(i) = InputBox(Prompt)
Prompt = "Inserisci Età"
Età(i) = InputBox(Prompt)
DataArray(i - 1, 0) = Nome(i)
DataArray(i - 1, 1) = Età(i)
i = i + 1
Loop
'Trasferisce l'Array nel worksheet a partire dalla cella A2
ws.Range("A2").Resize(10, 2).Value = DataArray
'Salva il Workbook e esce da Excel
wb.SaveAs(Path)
excel.Quit()
MsgBox("I dati sono stati salvati in " & Path)
Labei1.Text = ("I dati sono stati salvati in " & Path)
End Sub
End Class
6. Excel: create a file, fill it
with data and save
Create
a
new
project.
From
the
Project
Menu
=>
Add
Reference
=>
Com,
add
the
Microsoft
Excel
reference.
Double
click
on
Form1
and enter the following lines of code
Gemini
2
l'ultima
versione
della
famosa
app
di
ricerca
duplicati
per
OS
X
della
MacPaw
una
delle
socetà
leader
nel
mondo
software
Mac.
Trova
e
rimuove
files
identici
o
simili
sul
vostro
Mac
Superveloce e
affidabile
Un Duplicate Files Manager
stellare anche per il Mac:
Un Duplicate Files Manager
per Windows
Trova
ed
elimina
i
file
doppi
con
pochi
clic del mouse
ScreenShotManager per catturare
immagini dello schermo, WebCam
e pagine Web.
Un'applicazione
completa,
facile
da
usare
e
da
tenere
pronta
all'uso
nella
Barra delle applicazion
A7. Convertire Asci in HEX e viceversa
Creare un progetto con due TextBox, due Button e due Label.
Scrivere il testo da convertire e cliccare sul relativo pulsante.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'ASCI to HEX
Dim str As String = TextBox1.Text
Dim byteArray() As Byte
Dim hexNumbers As System.Text.StringBuilder = New System.Text.StringBuilder
byteArray = System.Text.ASCIIEncoding.ASCII.GetBytes(str)
For i As Integer = 0 To byteArray.Length - 1
hexNumbers.Append(byteArray(i).ToString("x"))
Next
TextBox2.Text = (hexNumbers.ToString())
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'HEX to ASCI
Dim st As String = TextBox2.Text
Dim com As String
For x = 0 To st.Length - 1 Step 2
Dim k As String = st.Substring(x, 2)
com &= System.Convert.ToChar(System.Convert.ToUInt32(k, 16)).ToString()
Next
TextBox1.Text = (com) '
End Sub
End Class
Altro metodo per convertire HEX in ASCI:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'ASCI to HEX
Dim st As String = TextBox2.Text
Dim com As String
For x = 0 To st.Length - 1 Step 2
com &= ChrW(CInt("&H" & st.Substring(x, 2)))
Next
TextBox1.Text = (com)
End Sub
7. Excel: create a file, fill it
with data and save
Create
a
project
with
two
TextBoxes,
two Buttons and two Labels.
Write
the
text
to
be
converted
and
click on the corresponding button.
A8. Criptare e decriptare un file di testo
Creare un progetto con due Button. Creare e salvare nella cartella c:\Temp\ un file di testo
che chiamiamo test.txt.
L’applicazione cripta il file test.txt e lo salva come testcrip.txt, quindi lo decripta salvandolo
come test.txt. Dopo essere stato criptato, il file in ASCI originale viene eliminato. Anche il file
criptato, una volta decriptato, viene eliminato.
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'Cripta il file
Try
Dim myDESProvider As DESCryptoServiceProvider = New DESCryptoServiceProvider()
myDESProvider.IV = ASCIIEncoding.ASCII.GetBytes("00345678")
myDESProvider.Key = ASCIIEncoding.ASCII.GetBytes("00345678")
Dim myICryptoTransform As ICryptoTransform = myDESProvider.CreateEncryptor(myDESProvider.Key,
_myDESProvider.IV)
Dim ProcessFileStream As FileStream = New FileStream("c:\Temp\test.txt", FileMode.Open, _
FileAccess.Read)
Dim ResultFileStream As FileStream = New FileStream("c:\Temp\testCrip.txt", FileMode.Create,
_FileAccess.Write)
Dim myCryptoStream As CryptoStream = New CryptoStream(ResultFileStream, myICryptoTransform,
_CryptoStreamMode.Write)
Dim bytearrayinput(ProcessFileStream.Length - 1) As Byte
ProcessFileStream.Read(bytearrayinput, 0, bytearrayinput.Length)
myCryptoStream.Write(bytearrayinput, 0, bytearrayinput.Length)
myCryptoStream.Close()
ProcessFileStream.Close()
ResultFileStream.Close()
My.Computer.FileSystem.DeleteFile("c:\Temp\test.txt")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'Deripta il file
Try
Dim myDESProvider As DESCryptoServiceProvider = New DESCryptoServiceProvider()
'Le cifre della stringa devono essere otto ma possono essere cambiate
myDESProvider.Key = ASCIIEncoding.ASCII.GetBytes("00345678")
myDESProvider.IV = ASCIIEncoding.ASCII.GetBytes("00345678")
Dim DecryptedFile As FileStream = New FileStream("c:\Temp\testCrip.txt", FileMode.Open,
_FileAccess.Read)
Dim myICryptoTransform As ICryptoTransform = myDESProvider.CreateDecryptor(myDESProvider.Key,
_myDESProvider.IV)
Dim myCryptoStream As CryptoStream = New CryptoStream(DecryptedFile, myICryptoTransform,
_CryptoStreamMode.Read)
Dim myDecStreamReader As New StreamReader(myCryptoStream)
Dim myDecStreamWriter As New StreamWriter("c:\Temp\test.txt")
myDecStreamWriter.Write(myDecStreamReader.ReadToEnd())
myCryptoStream.Close()
myDecStreamReader.Close()
myDecStreamWriter.Close()
My.Computer.FileSystem.DeleteFile("c:\Temp\testCrip.txt")
Catch ex As Exception
End Try
End Sub
End Class
8. Encrypt and decrypt a text
file
Create
a
project
with
two
buttons.
Create
and
save
in
the
c:
\
Temp
\
folder a text file that we call test.txt.
The
application
encrypts
the
test.txt
file
and
saves
it
as
testcrip.txt,
then
decrypts
it
by
saving
it
as
test.txt.
After
being
encrypted,
the
original
ASCI
file
is
deleted.
Even
the
encrypted
file,
once
decrypted,
is
deleted
A9. Esempi di Process.Start
(Spazio dei nomi: Imports System.Diagnostics)
Per aprire un documento qualsiasi con l’applicazione predefinita, cioè quella associata alla
specifica estensione del documento:
Process.Start(“Percorso completo del file da aprire”)
Aprire un’applicazione presente nel Menù Start
Process.Start("winword") 'non occorre aggiungere .exe
Dim StartInfo As New ProcessStartInfo(“winword”)
StartInfo.WindowStyle = ProcessWindowStyle.Minimized
Process.Start(StartInfo)
Dim StartInfo As New ProcessStartInfo(“Chrome”)
StartInfo.WindowStyle = ProcessWindowStyle.Minimized
Process.Start(StartInfo)
StartInfo.Arguments = "www.vbnetapplications.com"
Process.Start(StartInfo)
Dim StartInfo As New ProcessStartInfo("Chrome", "codetips.vbnetapplications.com")
StartInfo.WindowStyle = ProcessWindowStyle.Normal
Process.Start(StartInfo)
Uso di “WindowsStyle” per aprire i Minimized o Hidden mode
Aprire un sito Web
Aprire un sito Web
Delete Empty Folder: elimina le
cartelle doppie dal tuo PC!
Con
pochi
clic
liberi
il
disco
da
centinaia
di cartelle inutilizzate!
A10. Download di un file da un server FTP
Imports System.Net
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim buffer(1023) As Byte ' Buffer lettura di 1kB
Dim bytesIn As Integer ' Numero di bytes letti
Dim totalBytesIn As Double ' Totale byte ricevuti (= filesize)
Dim output As IO.Stream ' Il file risposta da salvare
Try 'Catch l'errore se le credenziali sono errate
Dim FTPRequest As FtpWebRequest = DirectCast(WebRequest.Create("ftp://Percorso/Nome file"),
FtpWebRequest)
FTPRequest.Credentials = New NetworkCredential("Username", "Passwort")
FTPRequest.Method = WebRequestMethods.Ftp.DownloadFile
' Il server FTP risponde alla richiesta
Dim stream As IO.Stream = FTPRequest.GetResponse.GetResponseStream
'Scrive il contenuto nel file di destinazione (che può avere un nome diverso)
output = IO.File.Create("C:\Percorso\Nome file")
bytesIn = 1
Do Until bytesIn < 1 'Quando bytesIn = 0 il loop termina
bytesIn = stream.Read(buffer, 0, 1024) 'legge max 1024 bytes da mettere nel buffer
If bytesIn > 0 Then
output.Write(buffer, 0, bytesIn) 'scarica il buffer nel file
totalBytesIn += bytesIn 'calcola le dimensioni del file
Label1.Text = (totalBytesIn.ToString) + " Bytes Downloaded"
Application.DoEvents()
End IfLoop
output.Close()
stream.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
9. Examples of Process Start
10. Downloading a file from a
server
Gestione File - File Management
A11. Compara due file
A11. Compare files
Inserisci in Form1: 1 Button, 2 TextBox, OpenFileDialog
Imports System.IO
Public Class Form1 'Scelta dei due file da comparare
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OpenFileDialog1.ShowDialog()
TextBox1.Text = OpenFileDialog1.FileName
OpenFileDialog1.ShowDialog()
TextBox2.Text = OpenFileDialog1.FileName
End Sub
Private Function FileCompare(ByVal file1 As String, ByVal file2 As String) As Boolean
Dim file1byte As Integer
Dim file2byte As Integer
Dim fs1 As FileStream
Dim fs2 As FileStream
Dim fileComp1 As String
Dim fileComp2 As String
Try
fileComp1 = TextBox1.Text
fileComp2 = TextBox2.Text
'Apre i file
fs1 = New FileStream(fileComp1, FileMode.Open)
fs2 = New FileStream(fileComp2, FileMode.Open)
Do
' Legge i byte di ciascun file
file1byte = fs1.ReadByte()
file2byte = fs2.ReadByte()
Loop While ((file1byte = file2byte) And (file1byte <> -1)) 'se i byte sono diversi si
ferma
' Chiude i file
fs1.Close()
fs2.Close()
Catch ex As Exception
End Try
Return ((file1byte - file2byte) = 0) 'Restituisce 0 se i due file sono uguali
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Confronta i due file
If (FileCompare(Me.TextBox1.Text, Me.TextBox2.Text)) Then
MessageBox.Show("I due files sono uguali", "Compara files")
Else
MessageBox.Show("I due files non sono uguali", "Compara files")
End If
End Sub
End Class
Insert in Form1: 1 Button, 2 TextBox,
OpenFileDialog