-1

I use File.Delete to delete a .exe file in the C drive. But it says I don't have access to delete it. Now I want to use File.Delete and File.Move to do it, I tried running VS with Admin rights but it didn't work. I want to work with C drive, not another drive. Thank you P/s: I tried the mentioned solutions with the same problem, but it didn't work for me.

File.Delete(@"C:\Program Files (x86)\ProgramName\FileName.exe");
File.Move(@"newFileName.exe", @"C:\Program Files (x86)\ProgramName\");
Ahmad
  • 770
  • 9
  • 21
D2K
  • 1
  • 4
  • 1
    don't bother with VS. what if you run the output exe with admin? – Lei Yang Mar 14 '22 at 05:43
  • 2
    There is a `"` missing at the end of line 2. Does this really compile? – Uwe Keim Mar 14 '22 at 05:44
  • because you didn’t specify the file name in arg2 in `File.Move`. Like that: `File.Move("C:\file.txt", "C\files\file.txt");`. **All** methods who work with files throw `Access to the path` if you DIDN'T specified the file name. – Aarnihauta Mar 14 '22 at 06:15
  • 1
    Windows restricts access to some secured path. you need to run as 'ADMIN' for this purpose. – Ahmad Mar 14 '22 at 07:26
  • 2
    Elevation required, look [here](https://stackoverflow.com/a/2818776/17034). The Move() call is wrong, you can't use it to overwrite a directory with a file. Fix with File.Move(@"newFileName.exe", @"C:\Program Files (x86)\ProgramName\FileName.exe"); – Hans Passant Mar 14 '22 at 08:11
  • When i run exe file with admin. Program auto close – D2K Mar 14 '22 at 10:50
  • sorry, in VS. this code is File.Move(@"newFileName.exe", @"C:\Program Files (x86)\ProgramName\"); – D2K Mar 14 '22 at 10:51
  • I has try run VS or exe file build with admin. But not work, i recive notications: Access to the path 'C is denied.'when run in VS. Program auto close when run with exe file build – D2K Mar 14 '22 at 10:52
  • I has use File.Delete first, and File.Move() after – D2K Mar 14 '22 at 10:54
  • Only the installer/uninstaller should be modifying files in `%ProgramFiles%` or `%ProgramFiles(x86)%`. – Tu deschizi eu inchid Mar 14 '22 at 13:02
  • @D2K: You do not need to build your app as admin, but you need to run/execute it as admin. – Luuk Mar 14 '22 at 13:11
  • I has try run exe with admin, but not work – D2K Mar 17 '22 at 12:32
  • @D2K after running as admin it is showing same error as denied path to c drive ? – Ahmad Mar 18 '22 at 11:06
  • No, it's auto close exe – D2K Mar 20 '22 at 12:38

1 Answers1

0

How do I force my .NET application to run as administrator?

Try checking out this link, your application should be running as administrator to have privilege and look for second solution which is provided by Hassan Rahman

I hope it will resolve your query.