Im trying to make an updater for my application but I keep getting exceptions when trying to delete the file or download the new file.
unauthorized access exception for file delete or webclient error for downloading new file. Ive tried setting the program to run as admin, the program that needs deleting is all normal, nothing set to read only or anything else that would make the update throw an exception. The file set to update is another app made in c#
This is what is suppose to happen:
Login System - prompt to update
Login System - download updater
Login System - exit or have update program exit
Updater - make sure all processes with name: Login System are not running
Updater - Delete Login System - Error - File access exception
Updater - Download latest version - Sometimes error usually if the file doesn't delete
Updater - start Login System
Updater - Exit
Login System - Check for updater.exe and delete on startup
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Diagnostics;
namespace Update
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Set program name and program download.
string ProgramName = "Login System.exe";
string DownloadLocation = "";
WebClient WC = new WebClient();
private void Form1_Load(object sender, EventArgs e)
{
//Check if the program is in the same folder as the update
if (File.Exists(ProgramName))
{
//Try to stop all running processes
Process[] RunningProcess = Process.GetProcessesByName(ProgramName.Replace(".exe", ""));
foreach (Process CurrentProcess in RunningProcess)
{
if (!CurrentProcess.HasExited)
{
try
{
CurrentProcess.CloseMainWindow();
CurrentProcess.Close();
CurrentProcess.Kill();
}
catch { }
}
}
}
else
{
MessageBox.Show("Unable to Access: " + ProgramName, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
//Delete old program
try
{
if (File.Exists(ProgramName))
{
File.Delete(ProgramName);
}
}
catch (Exception EX)
{
MessageBox.Show("Delete File " + EX.Message, "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
//Download new updated program
try
{
WC.DownloadFile(DownloadLocation, ProgramName);
}
catch (Exception EX)
{
MessageBox.Show("Download file " + EX.Message, "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
//Start program
try
{
if (File.Exists(ProgramName))
{
Process.Start(ProgramName);
}
}
catch (Exception EX)
{
MessageBox.Show(EX.Message, "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
//Close Updater
this.Close();
}
}
}