Option Strict On Imports System.IO Imports System.Net Imports System.Threading Public Class pctDownload Inherits PictureBox Dim b As Bitmap Dim g As Graphics Dim ft As New Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel) Dim f As IO.FileStream Dim m_Fichier, m_Destination As String Event Complet(ByVal Fichier As String) Delegate Sub Progress(ByVal Cours As Integer, ByVal Total As Integer) Public Sub New(ByVal Fichier As String, ByVal Destination As String, ByVal Largeur As Integer, ByVal Hauteur As Integer) With Me .Width = Largeur .Height = Hauteur .BorderStyle = Windows.Forms.BorderStyle.FixedSingle End With b = New Bitmap(Largeur, Hauteur) g = Graphics.FromImage(b) m_Fichier = Fichier m_Destination = Destination g.FillRectangle(Brushes.LightSteelBlue, b.GetBounds(GraphicsUnit.Pixel)) g.DrawString("0.00 %", ft, Brushes.White, Convert.ToInt32(Largeur / 2) - 15, 2) Me.Image = CType(b.Clone, Image) End Sub Public Sub Start() Dim t As New Thread(AddressOf Telecharge) t.Start() End Sub Private Sub Telecharge() Dim fic As String = m_Fichier.Substring(m_Fichier.LastIndexOf("/") + 1) Dim webr As WebRequest = HttpWebRequest.Create(m_Fichier) Dim webrequest As HttpWebRequest = DirectCast(webr, HttpWebRequest) Dim Length As Integer Dim rcvStream As Stream webrequest.Method = "GET" webrequest.Pipelined = False webrequest.KeepAlive = False webrequest.Credentials = New System.Net.CredentialCache webrequest.AuthenticationLevel = Security.AuthenticationLevel.MutualAuthRequested webrequest.Timeout = 9000 webrequest.ProtocolVersion = New Version(1, 1) webrequest.ContentType = "*/*" webrequest.AllowAutoRedirect = True webrequest.MaximumAutomaticRedirections = 10 Dim webrep As WebResponse = webrequest.GetResponse Dim webreponse As HttpWebResponse = DirectCast(webrep, HttpWebResponse) Length = Convert.ToInt32(webreponse.ContentLength) rcvStream = webreponse.GetResponseStream Dim buf(1024) As Byte Dim bytesread As Integer Dim fw As BinaryWriter = Nothing Try f = New FileStream(m_Destination & fic, FileMode.CreateNew) fw = New BinaryWriter(f) Catch Do Dim rd As New Random fic = rd.Next(0, 2000000).ToString & "_" & fic If My.Computer.FileSystem.FileExists(m_Destination & fic) = False Then Exit Do Loop f = New FileStream(m_Destination & fic, FileMode.OpenOrCreate) fw = New BinaryWriter(f) End Try Do bytesread = rcvStream.Read(buf, 0, buf.Length) fw.Write(buf, 0, bytesread) If Me.InvokeRequired Then Me.Invoke(New Progress(AddressOf Progression), Convert.ToInt32(f.Length), Length) Loop Until bytesread = 0 fw.Close() f.Close() End Sub Private Sub Progression(ByVal Cours As Integer, ByVal Total As Integer) g.FillRectangle(Brushes.LightSteelBlue, b.GetBounds(GraphicsUnit.Pixel)) Dim c As New Rectangle(0, 0, Convert.ToInt32((Cours / Total) * b.Width), b.Height) g.FillRectangle(Brushes.SteelBlue, c) Dim lft As SizeF = g.MeasureString(String.Format("{0:0.00%}", Cours / Total), ft, SizeF.Empty, StringFormat.GenericDefault) g.DrawString(String.Format("{0:0.00%}", Cours / Total), ft, Brushes.White, Convert.ToInt32((b.Width / 2) - (lft.Width / 2)), 2) Me.Image = CType(b.Clone, Image) If Cours = Total Then RaiseEvent Complet(m_Fichier) End If End Sub Friend WithEvents Button1 As System.Windows.Forms.Button Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar Private Sub InitializeComponent() Me.Button1 = New System.Windows.Forms.Button() Me.ProgressBar1 = New System.Windows.Forms.ProgressBar() CType(Me, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(0, 0) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(75, 23) Me.Button1.TabIndex = 0 Me.Button1.Text = "Button1" Me.Button1.UseVisualStyleBackColor = True ' 'ProgressBar1 ' Me.ProgressBar1.Location = New System.Drawing.Point(0, 0) Me.ProgressBar1.Name = "ProgressBar1" Me.ProgressBar1.Size = New System.Drawing.Size(100, 23) Me.ProgressBar1.TabIndex = 0 CType(Me, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub End Class Public Class Form1 'déclaration du picturebox avec son événement Dim WithEvents ProgressB As pctDownload Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'si les fichiers listelocale.txt et liste.txt existent, on les suppriment If My.Computer.FileSystem.FileExists(Application.StartupPath & "\listelocale.txt") Then My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\listelocale.txt") End If If My.Computer.FileSystem.FileExists(Application.StartupPath & "\liste.txt") Then My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\liste.txt") End If Dim repertoire() As IO.FileInfo = New IO.DirectoryInfo(Application.StartupPath).GetFiles("*", IO.SearchOption.AllDirectories) 'écriture de la liste locale des fichiers Using writer As New IO.StreamWriter(Application.StartupPath & "\listelocale.txt", False, System.Text.Encoding.Default) For Each fichier As IO.FileInfo In repertoire 'avec leur nom et leur MD5 séparé par un espace 'Note: le choix de l'espace pour la séparation n'est peut-être pas judicieux 'utiliser New Char() {Convert.ToChar(1)} pour un meilleur séparateur 'utilise fichier.FullName pour écrire le chemin complet du fichier Dim fichier_p As String = fichier.FullName.Replace(Application.StartupPath, "").Substring(1) writer.WriteLine(fichier_p & " " & MD5File(fichier.FullName)) Next End Using 'instanciation de la classe ProgressB = New pctDownload("http://monsite.fr/updater/liste.txt", Application.StartupPath & "", 200, 22) 'ajout de la picturebox au formulaire Me.Controls.Add(ProgressB) 'démarrage du téléchargement ProgressB.Start() End Sub 'si les fichiers listelocale.txt et liste.txt existent, on les suppriment 'fonction de hashage MD5 Private Function MD5File(ByVal nFichier As String) As String Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider Dim fmd5 As New IO.FileStream(nFichier, IO.FileMode.Open, IO.FileAccess.Read) md5.ComputeHash(fmd5) Dim hash As Byte() = md5.Hash Dim buff As System.Text.StringBuilder = New System.Text.StringBuilder Dim hashByte As Byte For Each hashByte In hash buff.Append(String.Format("{0:X2}", hashByte)) Next md5.Clear() fmd5.Close() fmd5.Dispose() Return buff.ToString End Function End Class
Option Strict On Imports System.IO Imports System.Net Imports System.Threading Public Class pctDownload Inherits PictureBox Dim b As Bitmap Dim g As Graphics Dim ft As New Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel) Dim f As IO.FileStream Dim m_Fichier, m_Destination As String Event Complet(ByVal Fichier As String) Delegate Sub Progress(ByVal Cours As Integer, ByVal Total As Integer) Public Sub New(ByVal Fichier As String, ByVal Destination As String, ByVal Largeur As Integer, ByVal Hauteur As Integer) With Me .Width = Largeur .Height = Hauteur .BorderStyle = Windows.Forms.BorderStyle.FixedSingle End With b = New Bitmap(Largeur, Hauteur) g = Graphics.FromImage(b) m_Fichier = Fichier m_Destination = Destination g.FillRectangle(Brushes.LightSteelBlue, b.GetBounds(GraphicsUnit.Pixel)) g.DrawString("0.00 %", ft, Brushes.White, Convert.ToInt32(Largeur / 2) - 15, 2) Me.Image = CType(b.Clone, Image) End Sub Public Sub Start() Dim t As New Thread(AddressOf Telecharge) t.Start() End Sub Private Sub Telecharge() Dim fic As String = m_Fichier.Substring(m_Fichier.LastIndexOf("/") + 1) Dim webr As WebRequest = HttpWebRequest.Create(m_Fichier) Dim webrequest As HttpWebRequest = DirectCast(webr, HttpWebRequest) Dim Length As Integer Dim rcvStream As Stream webrequest.Method = "GET" webrequest.Pipelined = False webrequest.KeepAlive = False webrequest.Credentials = New System.Net.CredentialCache webrequest.AuthenticationLevel = Security.AuthenticationLevel.MutualAuthRequested webrequest.Timeout = 9000 webrequest.ProtocolVersion = New Version(1, 1) webrequest.ContentType = "*/*" webrequest.AllowAutoRedirect = True webrequest.MaximumAutomaticRedirections = 10 Dim webrep As WebResponse = webrequest.GetResponse Dim webreponse As HttpWebResponse = DirectCast(webrep, HttpWebResponse) Length = Convert.ToInt32(webreponse.ContentLength) rcvStream = webreponse.GetResponseStream Dim buf(1024) As Byte Dim bytesread As Integer Dim fw As BinaryWriter = Nothing Try f = New FileStream(m_Destination & fic, FileMode.CreateNew) fw = New BinaryWriter(f) Catch Do Dim rd As New Random fic = rd.Next(0, 2000000).ToString & "_" & fic If My.Computer.FileSystem.FileExists(m_Destination & fic) = False Then Exit Do Loop f = New FileStream(m_Destination & fic, FileMode.OpenOrCreate) fw = New BinaryWriter(f) End Try Do bytesread = rcvStream.Read(buf, 0, buf.Length) fw.Write(buf, 0, bytesread) If Me.InvokeRequired Then Me.Invoke(New Progress(AddressOf Progression), Convert.ToInt32(f.Length), Length) Loop Until bytesread = 0 fw.Close() f.Close() End Sub Private Sub Progression(ByVal Cours As Integer, ByVal Total As Integer) g.FillRectangle(Brushes.LightSteelBlue, b.GetBounds(GraphicsUnit.Pixel)) Dim c As New Rectangle(0, 0, Convert.ToInt32((Cours / Total) * b.Width), b.Height) g.FillRectangle(Brushes.SteelBlue, c) Dim lft As SizeF = g.MeasureString(String.Format("{0:0.00%}", Cours / Total), ft, SizeF.Empty, StringFormat.GenericDefault) g.DrawString(String.Format("{0:0.00%}", Cours / Total), ft, Brushes.White, Convert.ToInt32((b.Width / 2) - (lft.Width / 2)), 2) Me.Image = CType(b.Clone, Image) If Cours = Total Then RaiseEvent Complet(m_Fichier) End If End Sub Friend WithEvents Button1 As System.Windows.Forms.Button Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar Private Sub InitializeComponent() Me.Button1 = New System.Windows.Forms.Button() Me.ProgressBar1 = New System.Windows.Forms.ProgressBar() CType(Me, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(0, 0) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(75, 23) Me.Button1.TabIndex = 0 Me.Button1.Text = "Button1" Me.Button1.UseVisualStyleBackColor = True ' 'ProgressBar1 ' Me.ProgressBar1.Location = New System.Drawing.Point(0, 0) Me.ProgressBar1.Name = "ProgressBar1" Me.ProgressBar1.Size = New System.Drawing.Size(100, 23) Me.ProgressBar1.TabIndex = 0 CType(Me, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub End Class Public Class Form1 'déclaration du picturebox avec son événement Dim WithEvents ProgressB As pctDownload Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'si les fichiers listelocale.txt et liste.txt existent, on les suppriment If My.Computer.FileSystem.FileExists(Application.StartupPath & "\listelocale.txt") Then My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\listelocale.txt") End If If My.Computer.FileSystem.FileExists(Application.StartupPath & "\liste.txt") Then My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\liste.txt") End If Dim repertoire() As IO.FileInfo = New IO.DirectoryInfo(Application.StartupPath).GetFiles("*", IO.SearchOption.AllDirectories) 'écriture de la liste locale des fichiers Using writer As New IO.StreamWriter(Application.StartupPath & "\listelocale.txt", False, System.Text.Encoding.Default) For Each fichier As IO.FileInfo In repertoire 'avec leur nom et leur MD5 séparé par un espace 'Note: le choix de l'espace pour la séparation n'est peut-être pas judicieux 'utiliser New Char() {Convert.ToChar(1)} pour un meilleur séparateur 'utilise fichier.FullName pour écrire le chemin complet du fichier Dim fichier_p As String = fichier.FullName.Replace(Application.StartupPath, "").Substring(1) writer.WriteLine(fichier_p & " " & MD5File(fichier.FullName)) Next End Using 'instanciation de la classe ProgressB = New pctDownload("http://www.taurusmt2.fr/updater/liste.txt", Application.StartupPath & "", 200, 22) 'ajout de la picturebox au formulaire Me.Controls.Add(ProgressB) 'démarrage du téléchargement ProgressB.Start() 'comparaison... Using reader_dist As New IO.StreamReader(Application.StartupPath & "\liste.txt") Do While Not reader_dist.EndOfStream 'lecture de la ligne du fichier Dim ligne_dist As String = reader_dist.ReadLine 'séparation des informations Dim fichier_dist As String = ligne_dist.Split(" "c)(0) Dim md5_dist As String = ligne_dist.Split(" "c)(1) Dim fichier_loc As String = "" Using reader_loc As New IO.StreamReader(Application.StartupPath & "\listelocale.txt") Dim fichierexiste As Boolean = False Do While Not reader_loc.EndOfStream Dim ligne_loc As String = reader_loc.ReadLine fichier_loc = ligne_loc.Split(" "c)(0) Dim md5_loc As String = ligne_loc.Split(" "c)(1) 'fichiers de même nom If fichier_dist = fichier_loc Then 'le md5 est différent If md5_dist <> md5_loc Then Debug.Print("md5 différent : téléchargement de " & fichier_dist) 'instanciation de la classe ProgressB = New pctDownload("http://monsite.fr/updater/pack/" & fichier_dist, Application.StartupPath & "" & fichier_dist, 200, 22) 'ajout de la picturebox au formulaire Me.Controls.Add(ProgressB) 'démarrage du téléchargement ProgressB.Start() Else 'le hash est le même (on peut effectuer une action ici) Debug.Print("fichier existe (md5 égal) " & fichier_dist) End If fichierexiste = True Exit Do End If Loop 'si le fichier n'existe pas on le télécharge If Not fichierexiste Then Debug.Print("fichier introuvable : telechargement de " & fichier_dist) 'instanciation de la classe ProgressB = New pctDownload("http://monsite.fr/updater/pack/" & fichier_dist, Application.StartupPath & "" & fichier_dist, 200, 22) 'ajout de la picturebox au formulaire Me.Controls.Add(ProgressB) 'démarrage du téléchargement ProgressB.Start() End If End Using Loop End Using End Sub 'si les fichiers listelocale.txt et liste.txt existent, on les suppriment 'fonction de hashage MD5 Private Function MD5File(ByVal nFichier As String) As String Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider Dim fmd5 As New IO.FileStream(nFichier, IO.FileMode.Open, IO.FileAccess.Read) md5.ComputeHash(fmd5) Dim hash As Byte() = md5.Hash Dim buff As System.Text.StringBuilder = New System.Text.StringBuilder Dim hashByte As Byte For Each hashByte In hash buff.Append(String.Format("{0:X2}", hashByte)) Next md5.Clear() fmd5.Close() fmd5.Dispose() Return buff.ToString End Function End Class
même quand ça ne bug pas on attend un peu avant que le téléchargement ne se lance. La ligne " Dim webrep As WebResponse = webrequest.GetResponse" est souvent citée.
L'interface ne se lance pas et j'obtiens une erreur Microsoft.NET Framework Could not find file "C:\Users\...\Debug\liste.txt
Il doit y avoir une autre fonction qui comme DownLoadFile empêche l'exécution du code.
Vous n’avez pas trouvé la réponse que vous recherchez ?
Posez votre questionUsing reader_dist As New IO.StreamReader(Application.StartupPath & "\liste.txt")
The process cannot access the file 'C:\Users\...\Projects\WindowsApplication5\WindowsApplication5\bin\Debug\liste.txt' because it is being used by another process.
Public Class Form1 'déclaration du picturebox avec son événement Dim WithEvents ProgressB As pctDownload Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'si les fichiers listelocale.txt et liste.txt existent, on les suppriment If My.Computer.FileSystem.FileExists(Application.StartupPath & "\listelocale.txt") Then My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\listelocale.txt") End If If My.Computer.FileSystem.FileExists(Application.StartupPath & "\liste.txt") Then My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\liste.txt") End If Dim repertoire() As IO.FileInfo = New IO.DirectoryInfo(Application.StartupPath).GetFiles("*", IO.SearchOption.AllDirectories) 'écriture de la liste locale des fichiers Using writer As New IO.StreamWriter(Application.StartupPath & "\listelocale.txt", False, System.Text.Encoding.Default) For Each fichier As IO.FileInfo In repertoire 'avec leur nom et leur MD5 séparé par un espace 'Note: le choix de l'espace pour la séparation n'est peut-être pas judicieux 'utiliser New Char() {Convert.ToChar(1)} pour un meilleur séparateur 'utilise fichier.FullName pour écrire le chemin complet du fichier Dim fichier_p As String = fichier.FullName.Replace(Application.StartupPath, "").Substring(1) writer.WriteLine(fichier_p & " " & MD5File(fichier.FullName)) Next End Using 'instanciation de la classe ProgressB = New pctDownload("http://www.monsite.fr/updater/liste.txt", Application.StartupPath & "", 200, 22) 'ajout de la picturebox au formulaire Me.Controls.Add(ProgressB) 'démarrage du téléchargement ProgressB.Start() End Sub Private Sub ProgressB_Complet(ByVal Fichier As String) Handles ProgressB.Complet 'ici tu peux lancer un autre téléchargement ... 'comparaison... Using reader_dist As New IO.StreamReader(Application.StartupPath & "\liste.txt") Do While Not reader_dist.EndOfStream 'lecture de la ligne du fichier Dim ligne_dist As String = reader_dist.ReadLine 'séparation des informations Dim fichier_dist As String = ligne_dist.Split(" "c)(0) Dim md5_dist As String = ligne_dist.Split(" "c)(1) Dim fichier_loc As String = "" Using reader_loc As New IO.StreamReader(Application.StartupPath & "\listelocale.txt") Dim fichierexiste As Boolean = False Do While Not reader_loc.EndOfStream Dim ligne_loc As String = reader_loc.ReadLine fichier_loc = ligne_loc.Split(" "c)(0) Dim md5_loc As String = ligne_loc.Split(" "c)(1) 'fichiers de même nom If fichier_dist = fichier_loc Then 'le md5 est différent If md5_dist <> md5_loc Then Debug.Print("md5 différent : téléchargement de " & fichier_dist) 'instanciation de la classe ProgressB = New pctDownload("http://www.monsite.fr/updater/pack/" & fichier_dist, Application.StartupPath & "" & fichier_dist, 200, 22) 'ajout de la picturebox au formulaire Me.Controls.Add(ProgressB) 'démarrage du téléchargement ProgressB.Start() Else 'le hash est le même (on peut effectuer une action ici) Debug.Print("fichier existe (md5 égal) " & fichier_dist) End If fichierexiste = True Exit Do End If Loop 'si le fichier n'existe pas on le télécharge If Not fichierexiste Then Debug.Print("fichier introuvable : telechargement de " & fichier_dist) 'instanciation de la classe ProgressB = New pctDownload("http://www.monsite.fr/updater/pack/" & fichier_dist, Application.StartupPath & "" & fichier_dist, 200, 22) 'ajout de la picturebox au formulaire Me.Controls.Add(ProgressB) 'démarrage du téléchargement ProgressB.Start() End If End Using Loop End Using End Sub 'si les fichiers listelocale.txt et liste.txt existent, on les suppriment 'fonction de hashage MD5 Private Function MD5File(ByVal nFichier As String) As String Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider Dim fmd5 As New IO.FileStream(nFichier, IO.FileMode.Open, IO.FileAccess.Read) md5.ComputeHash(fmd5) Dim hash As Byte() = md5.Hash Dim buff As System.Text.StringBuilder = New System.Text.StringBuilder Dim hashByte As Byte For Each hashByte In hash buff.Append(String.Format("{0:X2}", hashByte)) Next md5.Clear() fmd5.Close() fmd5.Dispose() Return buff.ToString End Function End Class
Public Class Form1 'déclaration du picturebox avec son événement Dim WithEvents ProgressB As pctDownload Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'si les fichiers listelocale.txt et liste.txt existent, on les suppriment If My.Computer.FileSystem.FileExists(Application.StartupPath & "\listelocale.txt") Then My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\listelocale.txt") End If If My.Computer.FileSystem.FileExists(Application.StartupPath & "\liste.txt") Then My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\liste.txt") End If Dim repertoire() As IO.FileInfo = New IO.DirectoryInfo(Application.StartupPath).GetFiles("*", IO.SearchOption.AllDirectories) 'écriture de la liste locale des fichiers Using writer As New IO.StreamWriter(Application.StartupPath & "\listelocale.txt", False, System.Text.Encoding.Default) For Each fichier As IO.FileInfo In repertoire 'avec leur nom et leur MD5 séparé par un espace 'Note: le choix de l'espace pour la séparation n'est peut-être pas judicieux 'utiliser New Char() {Convert.ToChar(1)} pour un meilleur séparateur 'utilise fichier.FullName pour écrire le chemin complet du fichier Dim fichier_p As String = fichier.FullName.Replace(Application.StartupPath, "").Substring(1) writer.WriteLine(fichier_p & " " & MD5File(fichier.FullName)) Next End Using 'instanciation de la classe ProgressB = New pctDownload("http://monsite.fr/updater/liste.txt", Application.StartupPath & "", 200, 22) 'ajout de la picturebox au formulaire Me.Controls.Add(ProgressB) 'démarrage du téléchargement ProgressB.Start() End Sub Private Sub ProgressB_Complet(ByVal Fichier As String) Handles ProgressB.Complet 'ici tu peux lancer un autre téléchargement ... End Sub 'si les fichiers listelocale.txt et liste.txt existent, on les suppriment 'fonction de hashage MD5 Private Function MD5File(ByVal nFichier As String) As String Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider Dim fmd5 As New IO.FileStream(nFichier, IO.FileMode.Open, IO.FileAccess.Read) md5.ComputeHash(fmd5) Dim hash As Byte() = md5.Hash Dim buff As System.Text.StringBuilder = New System.Text.StringBuilder Dim hashByte As Byte For Each hashByte In hash buff.Append(String.Format("{0:X2}", hashByte)) Next md5.Clear() fmd5.Close() fmd5.Dispose() Return buff.ToString End Function End Class