Click here to Skip to main content
Click here to Skip to main content

Application Auto Update Revisited

By , 19 Nov 2006
 

Introduction

Since my first iteration of the AutoUpdate, I noticed that I don't really need the ability to change the AutoUpdate program itself, so I don't need it. The second thing is that most of the time I don't need to update all the files.

What has changed

The AutoUpdate program (AutoUpdate.exe) is no longer required. Now, everything that is needed is in the DLL (AutoUpdate.dll). No need to touch the CommandLine anymore since everything is at the same place. The AutoUpdate doesn't need to be a class, now it is just a module, so, no need to create an AutoUpdate variable.

No need to change the AutoUpdate code. The remote path, the update file name, and the error message are now properties and the last two have default values.

The update file has a new layout, as shown:

<File Name>;<Version>   [' comments    ]
<File Name>[;<Version>] [' comments    ]

<File Name>[;?]         [' comments    ]
<File Name>[;delete]    [' comments    ]
...

And this is what it means:

  • Blank lines and comments are ignored.
  • The first line should be the current program/version.
  • From the second line to the end, the second parameter is optional.
  • If the second parameter is not specified, the file is updated.
  • If the version is specified, the update checks the version.
  • If the second parameter is an interrogation mark (?), the update checks if the file already exists, and "doesn't" upgrade if it exists.
  • If the second parameter is "delete", the system tries to delete the file.
  • "'" (chr(39)) starts a line comment (like VB).

The UpdateFiles function returns True if the AutoUpdate did the update or there was an error during the update, or False if nothing was done.

The auto update web folder

Some things never change. The auto update web folder should have a folder for each system you want to upgrade. The root folder is the one that you will refer on the RemotePath variable. Each sub folder should be named as the assembly name (normally, the program name without the extension). Inside the program folder, you save the files that you want to update and the file Update.txt (or the name that you defined in the UpdateFileName property) with the layout explained above.

Using the code

You can add the module to your project, or you can add a reference to the DLL. After that, you just need to call the UpdateFiles function. You also can change the default properties before the call.

Public Sub Main()
    ' You can set some parameters thru properties
    ' The remote path can be set thru the RemotePath property or 
    ' thru the RemotePath parameter in the function call
    ' UpdateFileName and ErrorMessages have default value so it's optional
    AutoUpdate.RemotePath = "http://www.url.com/directory/"

    ' the final location to the files will be RemotePath + AssembyName + "/" + FileName
    ' ex: http://www.url.com/directory/AutoUpdateTest/MyUpdate.dat

    AutoUpdate.UpdateFileName = "MyUpdate.dat"
    AutoUpdate.ErrorMessage = "Something funny is going on trying to auto update."

    ' test if an update is needed and quit the program if so.
    If AutoUpdate.UpdateFiles() Then Exit Sub

    ' here goes your regular code in the main sub
    Application.Run(New Form1)
End Sub

What else can be done

In the server side, you can build a service that automatically generates the update file, but this is up to you!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Eduardo Oliveira
Web Developer
Canada Canada
Member
Eduardo Oliveira graduated in Computer Systems Analysis in Rio de Janeiro - Brazil in 1990.
He has been working as Programmer Analyst since.
In 2001 immigrated to Canada and today lives in Calgary and works with .NET and SQL server/Sybase, developing Client/Server applications and ASP.NET server controls for CMS.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionthanks for sharingmemberSouthmountain15 Jun '12 - 12:53 
Excellent. I also appreciate who gave C# versions in the follow sections. I will try it in my software.
usability & truth

Generalupdated infoParam = "?" with a CompareFiles functionmembercreativesoul26 Feb '10 - 4:39 
Oi Eduardo,
 
tudo bem? (portuguese for how are you Smile | :) )
 
thanks for the code.
 
i updated it a bit by adding a comparefiles function when infoParam = "?" so it becomes 'updated only if it doesn't exist or file changed
 
regards,
 
Jason
QuestionAnyone having issues using this with VISTA platformmemberKebrite8 Feb '10 - 8:00 
G'day All,
 
First off, thanks for the code as I have been using this Auto Update functionality for over 6 months now and it's worked perfectly!
 
Now to the issue! This code has worked for me when the "client" part of my system is installed on Server or XP operating system and needs to auto upgrade. However, it won't auto update when it is installed on a VISTA operating system - in all three OS scenarios the "server" part of my system is installed on a Server 2003 OS.
 
I am in the process of setting up a development environment on a VISTA Enterprise system so I can step through my code but just wondering if anyone may know why the VISTA scenario fails? The user on the VISTA OS is an Administrator so it should not be a permissions thing. Also I have tried with a local Administrator and Domain Administrator account on the VISTA OS.
 
Any advise would be nice!
 
Cheers
Brendan
GeneralEnvironment.Exit(0)membertimjf26 Dec '09 - 14:16 
I'm not sure if anyone else has had problems using Application.Exit or Application.Restart but I could not get my application to work correctly until I used Environment.Exit(0)
 
Without using that method, my application would restart after the update but then get to a point and just close. I have yet to figure out why.
 
As an after thought, it may have something to do with my Shutdown mode and/or the fact that I have the application set to a single instance app.
 
Just thought I would spread this information.
 
Tim
GeneralRe: Environment.Exit(0)memberkeno2oo111 Sep '12 - 20:32 
I am having similar flakiness with a single-instance app. Thanks for the tip about Environment.exit(0). I plan to give that a try tomorrow.
GeneralRe: Environment.Exit(0)memberkeno2oo115 Sep '12 - 5:18 
It was the single instance app setting that was causing my problem.
GeneralI am lost on how to use this PLEASE HELP!memberGaby Bitar17 Dec '09 - 2:46 
Hey,
 
First of all when I download the Testprogram and DLL, when i try to open them in Visual Studios 2010 it tries to convert it and when it finishes there are errors while converting the program. Then the program does not run.
 
Second,
I am still lost on how to apply this to my program. I need like a step by step procedure on what to do with this.
 
Someone PLEASE HELP Smile | :)
 
Thanks
GeneralAutoUpdate with Download Form and Progressmemberammar7913 Dec '09 - 5:23 
Imports System.IO
Imports System.Net
Imports System.Diagnostics
Imports System.Threading
 
Public Module AutoUpdate
      Private m_RemotePath As String
      Private m_UpdateFileName As String = "Update.txt"
      Private m_ErrorMessage As String = "There was a problem runing the Auto Update."
      ' &lt;File Name&gt;;&lt;Version&gt;   [' comments      ]
      ' &lt;File Name&gt;[;&lt;Version&gt;] [' comments      ]  
      ' &lt;File Name&gt;[;?]            [' comments      ]
      ' &lt;File Name&gt;[;delete]      [' comments      ]
      ' ...
      ' Blank lines and comments are ignored
      ' The first line should be the current program/version
      ' from the second line to the end the second parameter is optional
      ' if the second parameter is not specified the file is updated.
      ' if the version is specified the update checks the version
      ' if the second parameter is an interrogation mark (?) the update checks if the
      ' file alredy exists and "don't" upgrade if exists.
      ' if the second parameter is "delete" the system try to delete the file
      ' "'" (chr(39)) start a line comment (like vb)
 
      ' Function Return Value
      ' True means that the program needs to exit because: the autoupdate did the update
      ' or there was an error during the update
      ' False - nothing was done
 
      Public Sub CheckForUpdate()
            Try
                  Dim b As Boolean = UpdateFiles(RemotePath)
                  If b Then
                        Application.Exit()
                  Else
                        MsgBox("You have the latest version of " + My.Application.Info.ProductName, MsgBoxStyle.OkOnly + MsgBoxStyle.Information)
                  End If
            Catch ex As Exception
            End Try
      End Sub
 
      Public Function UpdateFiles(Optional ByVal RemotePath As String = "") As Boolean
            If RemotePath = "" Then RemotePath = m_RemotePath Else m_RemotePath = RemotePath
 
            Dim Ret As Boolean = False
            Dim AssemblyName As String = System.Reflection.Assembly.GetEntryAssembly.GetName.Name
            Dim ToDeleteExtension As String = ".ToDelete"
            Dim RemoteUri As String = RemotePath &amp; AssemblyName &amp; "/"
            Dim MyWebClient As New WebClient
            Try
                  ' try to delete old files if exist
                  Dim s As String = Dir(My.Application.Info.DirectoryPath &amp; "\*" &amp; ToDeleteExtension)
                  Do While s &lt;&gt; ""
                        Try
                              File.Delete(My.Application.Info.DirectoryPath &amp; "\" &amp; s)
                        Catch ex As Exception
                        End Try
                        s = Dir()
                  Loop
                  ' get the update file content
                  Dim Contents As String = MyWebClient.DownloadString(RemoteUri &amp; UpdateFileName)
                  ' Process the autoupdate
                  ' get rid of the line feeds if exists
                  Contents = Replace(Contents, Chr(Keys.LineFeed), "")
                  Dim FileList() As String = Split(Contents, Chr(Keys.Return))
                  Contents = ""
                  ' Remove all comments and blank lines
                  For Each F As String In FileList
                        If InStr(F, "'") &lt;&gt; 0 Then F = Strings.Left(F, InStr(F, "'") - 1)
                        If F.Trim &lt;&gt; "" Then
                              If Contents &lt;&gt; "" Then Contents += Chr(Keys.Return)
                              Contents += F.Trim
                        End If
                  Next
                  ' rebuild the file list
                  FileList = Split(Contents, Chr(Keys.Return))
                  Dim Info() As String = Split(FileList(0), ";")
                  ' if the name is correct and it is a new version
                  If My.Application.Info.DirectoryPath.ToLower &amp; "\" &amp; Info(0).ToLower = My.Application.Info.DirectoryPath.ToLower + "\" + My.Application.Info.ProductName.ToLower + ".exe" AndAlso _
                              GetVersion(Info(1)) &gt; GetVersion(My.Application.Info.Version.ToString) Then
                        ' process files in the list
                        For Each F As String In FileList
                              Info = Split(F, ";")
                              Dim isToDelete As Boolean = False
                              Dim isToUpgrade As Boolean = False
                              Dim TempFileName As String = My.Application.Info.DirectoryPath &amp; "\" &amp; Now.TimeOfDay.TotalMilliseconds
                              Dim FileName As String = My.Application.Info.DirectoryPath &amp; "\" &amp; Info(0).Trim
                              Dim FileExists As Boolean = File.Exists(FileName)
                              If Info.Length = 1 Then
                                    ' Just the file as parameter always upgrade
                                    isToUpgrade = True
                                    isToDelete = FileExists
                              ElseIf Info(1).Trim = "delete" Then
                                    ' second parameter is "delete"
                                    isToDelete = FileExists
                              ElseIf Info(1).Trim = "?" Then
                                    ' second parameter is "?" (check if file exists and don't upgrade if exists)
                                    isToUpgrade = Not FileExists
                              ElseIf FileExists Then
                                    ' verify the file version
                                    Dim fv As FileVersionInfo = FileVersionInfo.GetVersionInfo(FileName)
                                    isToUpgrade = (GetVersion(Info(1).Trim) &gt; GetVersion(fv.FileMajorPart &amp; "." &amp; fv.FileMinorPart &amp; "." &amp; fv.FileBuildPart &amp; "." &amp; fv.FilePrivatePart))
                                    isToDelete = isToUpgrade
                              Else
                                    ' the second parameter exists as version number and the file doesn't exists
                                    isToUpgrade = True
                              End If
                              'Debug.Print(TempFileName)
                              ' download the new file
                              'If isToUpgrade Then MyWebClient.DownloadFile(RemoteUri &amp; Info(0), TempFileName)
                              '
                              If isToUpgrade Then
                                    Dim fDownload As New frmDownload(RemoteUri &amp; Info(0), TempFileName)
                                    If fDownload.ShowDialog() = DialogResult.Abort Then
                                          ' rename the existent file to be deleted in the future
                                          If isToDelete Then File.Move(FileName, TempFileName &amp; ToDeleteExtension)
                                          ' rename the downloaded file to the real name
                                          If isToUpgrade Then File.Move(TempFileName, FileName)
                                          ' try to delete the file
                                    End If
                              End If
 
                        Next
                        ' call the new version
                        System.Diagnostics.Process.Start(Application.ExecutablePath, Microsoft.VisualBasic.Command())
                        Ret = True
                  End If
            Catch ex As Exception
                  Ret = True
                  MsgBox(m_ErrorMessage &amp; vbCr &amp; ex.Message &amp; vbCr &amp; "Assembly: " &amp; AssemblyName, MsgBoxStyle.Critical, Application.ProductName)
            End Try
            Return Ret
      End Function
      Private Sub FileDownloadComplete()
 
      End Sub
      Public Property RemotePath() As String
            Get
                  Return m_RemotePath
            End Get
            Set(ByVal value As String)
                  m_RemotePath = value
            End Set
      End Property
 
      Public Property UpdateFileName() As String
            Get
                  Return m_UpdateFileName
            End Get
            Set(ByVal value As String)
                  m_UpdateFileName = value
            End Set
      End Property
 
      Public Property ErrorMessage() As String
            Get
                  Return m_ErrorMessage
            End Get
            Set(ByVal value As String)
                  m_ErrorMessage = value
            End Set
      End Property
 
      Private Function GetVersion(ByVal Version As String) As String
            Dim x() As String = Split(Version, ".")
            Return String.Format("{0:00000}{1:00000}{2:00000}{3:00000}", Int(x(0)), Int(x(1)), Int(x(2)), Int(x(3)))
      End Function
 
      Public Sub MakeFolderToUpload()
            Try
                  Dim fn As String = My.Application.Info.DirectoryPath + "\" + My.Application.Info.AssemblyName + ".exe"
                  Dim fnNew As String = "C:\" + My.Application.Info.ProductName + "\" + My.Application.Info.AssemblyName + ".exe"
 
                  If IO.Directory.Exists("C:\" + My.Application.Info.ProductName) Then
                        Try
                              IO.Directory.Delete("C:\" + My.Application.Info.ProductName, True)
                        Catch ex As Exception
                              If IO.File.Exists(fnNew) Then IO.File.Delete(fnNew)
                        End Try
                  End If
                  Application.DoEvents()
                  IO.Directory.CreateDirectory("C:\" + My.Application.Info.ProductName)
                  IO.File.Copy(fn, fnNew, True)
                  Dim rtb As New RichTextBox
                  rtb.AppendText(My.Application.Info.AssemblyName + ".exe;" + My.Application.Info.Version.ToString)
                  rtb.SaveFile("C:\" + My.Application.Info.ProductName + "\update.txt", RichTextBoxStreamType.PlainText)
            Catch ex As Exception
            End Try
      End Sub
End Module
 
Public Class frmDownload
      Inherits System.Windows.Forms.Form
 
      Private WithEvents tmrDownload As System.Windows.Forms.Timer
      Private WithEvents tmrNext As System.Windows.Forms.Timer
 
#Region " Windows Form Designer generated code "
 
      'Form overrides dispose to clean up the component list.
      Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                  If Not (components Is Nothing) Then
                        components.Dispose()
                  End If
            End If
            MyBase.Dispose(disposing)
      End Sub
 
      'Required by the Windows Form Designer
      Private components As System.ComponentModel.IContainer
      'NOTE: The following procedure is required by the Windows Form Designer
      'It can be modified using the Windows Form Designer.  
      'Do not modify it using the code editor.
      Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar
      Friend WithEvents Label1 As System.Windows.Forms.Label
      Friend WithEvents st2Speed As System.Windows.Forms.Label
      Friend WithEvents st2Downloded As System.Windows.Forms.Label
      Friend WithEvents st2DownloadURL As System.Windows.Forms.Label
      Friend WithEvents st2LocalFile As System.Windows.Forms.Label
      Friend WithEvents lblCent As System.Windows.Forms.Label
      &lt;System.Diagnostics.DebuggerStepThrough()&gt; Private Sub InitializeComponent()
            Me.ProgressBar1 = New System.Windows.Forms.ProgressBar
            Me.Label1 = New System.Windows.Forms.Label
            Me.st2Speed = New System.Windows.Forms.Label
            Me.st2Downloded = New System.Windows.Forms.Label
            Me.st2DownloadURL = New System.Windows.Forms.Label
            Me.st2LocalFile = New System.Windows.Forms.Label
            Me.lblCent = New System.Windows.Forms.Label
            Me.SuspendLayout()
            '
            'ProgressBar1
            '
            Me.ProgressBar1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                              Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.ProgressBar1.Location = New System.Drawing.Point(117, 73)
            Me.ProgressBar1.Name = "ProgressBar1"
            Me.ProgressBar1.Size = New System.Drawing.Size(315, 24)
            Me.ProgressBar1.TabIndex = 10
            '
            'Label1
            '
            Me.Label1.Location = New System.Drawing.Point(24, 73)
            Me.Label1.Name = "Label1"
            Me.Label1.Size = New System.Drawing.Size(53, 24)
            Me.Label1.TabIndex = 8
            Me.Label1.Text = "Progress:"
            Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
            '
            'st2Speed
            '
            Me.st2Speed.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.st2Speed.Location = New System.Drawing.Point(280, 105)
            Me.st2Speed.Name = "st2Speed"
            Me.st2Speed.Size = New System.Drawing.Size(152, 16)
            Me.st2Speed.TabIndex = 12
            Me.st2Speed.Text = "Transfer Rate:   KB/Sec"
            Me.st2Speed.TextAlign = System.Drawing.ContentAlignment.MiddleRight
            '
            'st2Downloded
            '
            Me.st2Downloded.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                              Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.st2Downloded.Location = New System.Drawing.Point(24, 105)
            Me.st2Downloded.Name = "st2Downloded"
            Me.st2Downloded.Size = New System.Drawing.Size(240, 16)
            Me.st2Downloded.TabIndex = 11
            Me.st2Downloded.Text = "Downloaded"
            Me.st2Downloded.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
            '
            'st2DownloadURL
            '
            Me.st2DownloadURL.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                              Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.st2DownloadURL.Location = New System.Drawing.Point(24, 9)
            Me.st2DownloadURL.Name = "st2DownloadURL"
            Me.st2DownloadURL.Size = New System.Drawing.Size(408, 32)
            Me.st2DownloadURL.TabIndex = 6
            Me.st2DownloadURL.Text = "Download URL"
            '
            'st2LocalFile
            '
            Me.st2LocalFile.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                              Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.st2LocalFile.Location = New System.Drawing.Point(24, 41)
            Me.st2LocalFile.Name = "st2LocalFile"
            Me.st2LocalFile.Size = New System.Drawing.Size(408, 32)
            Me.st2LocalFile.TabIndex = 7
            Me.st2LocalFile.Text = "Local File Name"
            '
            'lblCent
            '
            Me.lblCent.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.lblCent.Location = New System.Drawing.Point(64, 73)
            Me.lblCent.Name = "lblCent"
            Me.lblCent.Size = New System.Drawing.Size(48, 24)
            Me.lblCent.TabIndex = 9
            Me.lblCent.Text = "%"
            Me.lblCent.TextAlign = System.Drawing.ContentAlignment.MiddleRight
            '
            'frmDownload
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(456, 130)
            Me.ControlBox = False
            Me.Controls.Add(Me.Label1)
            Me.Controls.Add(Me.ProgressBar1)
            Me.Controls.Add(Me.st2Speed)
            Me.Controls.Add(Me.st2Downloded)
            Me.Controls.Add(Me.st2DownloadURL)
            Me.Controls.Add(Me.st2LocalFile)
            Me.Controls.Add(Me.lblCent)
            Me.MaximizeBox = False
            Me.Name = "frmDownload"
            Me.ShowIcon = False
            Me.ShowInTaskbar = False
            Me.Text = "Download"
            Me.ResumeLayout(False)
 
      End Sub
 
#End Region
#Region " Declarations "
      Dim UrlOfFile As String
      Dim LocOfFile As String
      Dim MainForm As Form
      Dim bPaused As Boolean
      Public Sub New(ByVal f As Form, ByVal sURL2Download As String, ByVal sLocalFilename As String)
            MyBase.New()
 
            'This call is required by the Windows Form Designer.
            InitializeComponent()
 
            Me.Text = Application.ProductName + " Update"
            'Add any initialization after the InitializeComponent() call
            Me.UrlOfFile = sURL2Download
            Me.LocOfFile = sLocalFilename
            'Me.SizeOfFile = FileSize
            Me.MainForm = f
            'Me.ProgressBar1
            'Me._NumberOfDownload = NumberOfDownload.MoreDownload
      End Sub
      Public Sub New(ByVal sURL2Download As String, ByVal sLocalFilename As String)
            MyBase.New()
            'This call is required by the Windows Form Designer.
            InitializeComponent()
            Me.Text = Application.ProductName + " Update"
 
            Me.UrlOfFile = sURL2Download
            Me.LocOfFile = sLocalFilename
      End Sub
      Private Sub WaitMinimize()
            Thread.Sleep(100)
            'Me.ShowHide()
      End Sub
#End Region
#Region " Menus "
      Private Sub mnuShowHide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            'Me.ShowHide()
      End Sub
      Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Me.Close()
      End Sub
      Private Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)
            'Me.ShowHide()
      End Sub
      Private Sub ShowHide1()
            If Me.Visible = True Then
                  Me.WindowState = FormWindowState.Minimized
                  Me.Hide()
            Else
                  Me.Show()
                  Me.Focus()
                  Me.WindowState = FormWindowState.Normal
            End If
      End Sub
      Dim DownloadedTemp As Double
      Dim Downloaded As Double
      Private Sub tmrDownload_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrDownload.Tick
            Application.DoEvents()
            DownloadedTemp = Downloaded / 1000
            Downloaded = 0
            'bitsec.Text = Format(DownloadedTemp, "#,###,###,###0.00") &amp; " KB/sec"
            Me.st2Speed.Text = "Transfer Rate: " &amp; Format(DownloadedTemp, "#,###,###,###0.00") &amp; " KB/sec"
      End Sub
#End Region
      Dim iDownloadCount As Integer = 0
 
      Private Sub frmDownload_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim t As New Threading.Thread(AddressOf Me.WaitMinimize)
            t.Start()
 
            If Me.UrlOfFile.Trim.Length &lt; 7 Then
                  Me.Close()
            End If
            Me.tmrNext.Start()
      End Sub
      Private Sub tmrNext_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrNext.Tick
            Try
                  If My.Computer.Network.IsAvailable Then
                        Me.tmrNext.Stop()
                        If Me.iDownloadCount &gt;= 3 Then
 
                              Me.Close()
                              Exit Try
                        End If
                        Me.iDownloadCount += 1
                        Dim StartTime As DateTime = Now
                        Dim fn As String = Me.DownloadFile(Me.UrlOfFile, Me.LocOfFile)
                        If IO.File.Exists(fn) Then
                              Me.DialogResult = Windows.Forms.DialogResult.Abort
                              Me.Close()
                        Else
                              Me.Timer(10)
                              Me.tmrNext.Start()
                        End If
                  End If
            Catch ex As Exception
                  Me.Timer(10)
                  Me.tmrNext.Start()
            End Try
      End Sub
      Private Function Timer(ByVal i As Integer) As Integer
            Return i * 1000
      End Function
      Private Function DownloadFile(ByVal sURL As String, ByVal sDownloadLocation As String) As String
            If Not IO.Directory.Exists(My.Computer.FileSystem.SpecialDirectories.Temp) Then
                  IO.Directory.CreateDirectory(My.Computer.FileSystem.SpecialDirectories.Temp)
            End If
            Dim sLocalTempFile As String = Me.LocOfFile
 
            Try
                  Me.st2DownloadURL.Text = "Downloading from: " &amp; sURL
                  Me.st2LocalFile.Text = "Saving to: " &amp; sLocalTempFile
 
                  Dim URLReq As Net.HttpWebRequest
                  Dim URLRes As Net.HttpWebResponse
 
                  Dim bBuffer(999) As Byte
                  Dim iBytesRead As Integer
 
                  Application.DoEvents()
 
                  URLReq = System.Net.WebRequest.Create(sURL)
                  URLRes = URLReq.GetResponse
                  Dim sChunks As IO.Stream = URLReq.GetResponse.GetResponseStream
 
                  Me.ProgressBar1.Value = 0
                  Me.ProgressBar1.Maximum = URLRes.ContentLength
 
                  Dim FileStreamer As New IO.FileStream(sLocalTempFile, IO.FileMode.Create)
 
                  tmrDownload.Start()
 
                  Do
                        If My.Computer.Network.IsAvailable Then
                              Try
                                    If Me.bPaused = True Then
                                          Do
                                                Application.DoEvents()
                                                If Me.bPaused = False Then
                                                      Exit Do
                                                End If
                                          Loop
                                    End If
                                    iBytesRead = sChunks.Read(bBuffer, 0, 1000)
 
                                    Downloaded += iBytesRead
                                    Me.st2Downloded.Text = "Downloaded " &amp; Format(Me.ProgressBar1.Value / 1024, "#,###,###,###0.00") &amp; " KB of " &amp; Format(Me.ProgressBar1.Maximum / 1024, "#,###,###,###0.00") &amp; " KB"
                                    Application.DoEvents()
                                    If Me.ProgressBar1.Value + iBytesRead &lt;= Me.ProgressBar1.Maximum Then
                                          Me.ProgressBar1.Value += iBytesRead
                                    Else
                                          Me.ProgressBar1.Value = Me.ProgressBar1.Maximum
                                    End If
                                    Try
                                          Me.lblCent.Text = ((Me.ProgressBar1.Value / Me.ProgressBar1.Maximum) * 100).ToString("##") &amp; "%"
                                    Catch ex As Exception
                                    End Try
 
                                    FileStreamer.Write(bBuffer, 0, iBytesRead)
                              Catch ex As Exception
                                    Exit Do
                              End Try
                        Else
                              Exit Do
                        End If
                  Loop Until iBytesRead = 0
 
                  Downloaded = 0
                  Me.tmrDownload.Stop()
 
                  sChunks.Close()
                  FileStreamer.Close()
 
                  Return sLocalTempFile
            Catch ex1 As Net.WebException
            Catch ex As Exception
            End Try
            Me.tmrDownload.Stop()
            Return ""
      End Function
End Class
GeneralRe: AutoUpdate with Download Form and Progress [modified]memberKyferEz8 Nov '10 - 10:50 
Bug
This line:
My.Application.Info.DirectoryPath.ToLower + "\" + My.Application.Info.ProductName.ToLower + ".exe"
 
should be replaced with this:
My.Application.Info.DirectoryPath.ToLower + "\" + My.Application.Info.AssemblyName.ToLower + ".exe"
 
Also I had to comment out the declarations of tmrDownload and tmrNext and add them to the form designer to make them work. For some reason they just wouldn't fire till I did that.

modified on Monday, November 8, 2010 5:38 PM

GeneralThe process cannot access the file because it is being used by another processmemberNgonidzashe Munyikwa24 Jul '09 - 2:32 
The code in AutoUpdate is working up to the line
 
System.Diagnostics.Process.Start(Application.ExecutablePath, Microsoft.VisualBasic.Command())
 
then I'm getting this error message guys,
 
"The process cannot access the file because it is being used by another process"
 
How can i solve this, ideas ???

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 19 Nov 2006
Article Copyright 2006 by Eduardo Oliveira
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid