Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve System.Unauthorized access exception?

Tags:

c#

exception

I have add updater for an application (Myapp.exe). When I launch Myapp.exe then it checks the new available version and download it according to users instruction into Windows Temp directory. After downloading the update to Temp directory, the new program replacer.exe runs which is responsible to get Myapp.exe, kill its process, delete Myapp.exe and copy new version (of Myapp.exe) from Temp directory to Myapp.exe old path. The replacer.exe has following code.

class Program
    {
        static void Main(string[] args)
        {
            try
            {                       
                Process myProcess = Process.GetProcessesByName("Myapp")[0];    
                myProcess.Kill();
                File.Delete(args[0]);
                File.Copy(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Temp\\Myapp.exe", args[0], false);

            }
            catch (Exception e)
            {
                Console.Write(e.ToString() + "");
                //return;
            }               
            //Console.Write( "Success");
            try
            {
                Process.Start(args[0]);
            }
            catch (Exception es) 
            {
                Console.Write(es.ToString() + "");
                //return;
            }
            Console.ReadLine();
        }
    }

But replacer.exe unable to delete Myapp.exe and give exception System.UnauthorizedAccessException. Thats mean the replacer.exe cannot access the path given by Myapp.exe while deleting Myapp.exe Note: I have run UserAccount, Myapp.exe and replacer.exe as Administrator and Normal user as well. How can I resolve it. Please help me. Thanks in advance. . .

like image 385
NASSER Avatar asked Feb 15 '26 23:02

NASSER


1 Answers

It takes a little while for a process to end: Process.Kill() merely tells the process to stop, but doesn't want for it to actually finish.

You'll want to introduce a loop with a short delay and a check to see if the process has actually terminated.

Use the property Process.HasExited to check this: documentation on MSDN here: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.hasexited.aspx.

like image 159
Jeremy McGee Avatar answered Feb 18 '26 13:02

Jeremy McGee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!