0

Sometimes I need to delete or replace a dll file in system32 folder of windows 7.
The code below always has Permission Denied Error :

            if (File.Exists(@"C:\Windows\system32\mydll.dll"))
            {
                fileInfo.IsReadOnly = false;
                File.Delete(@"C:\Windows\system32\mydll.dll");
            }

How can I bypass this error and replace a file in system32 folder?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
SilverLight
  • 19,668
  • 65
  • 192
  • 300
  • 2
    You either need administrator privileges, right click the program and select "Run as Administrator"/edit the app manifest to prompt for it, or your account does not have permission to make change to the system folder. If the DLL is loaded into memory I don't know if you can delete it. – 0_______0 Sep 08 '12 at 20:56
  • @0_______0 thanks for the comment. but i am administrator... problem is still there. – SilverLight Sep 08 '12 at 20:59
  • By default I don't think you can delete/edit any system files without changing the permissions. Programmer's answer will take ownership of it and grant the permission to delete it. – 0_______0 Sep 08 '12 at 21:03
  • What happens if you try deleting the file manually, or through command prompt? Wondering if Windows give you the same problem. I also wonder why you've trying to do this. If it's a 'system' file, I'd highly advise deleting on a reboot task. – Arran Sep 08 '12 at 23:19

2 Answers2

2
if (File.Exists(@"C:\Windows\System32\mydll.dll"))
{
    new Process() { StartInfo = new ProcessStartInfo("cmd.exe", @"/k takeown /f C:\Windows\System32\mydll.dll && icacls C:\Windows\System32\mydll.dll /grant %username%:F") }.Start();
    File.Delete(@"C:\Windows\System32\mydll.dll");
}

Note that you can't delete a system DLL like shell32.dll even after taking ownership but you can rename or move it.

Elmo
  • 6,409
  • 16
  • 72
  • 140
  • thanks for the edit and comment. but i don't know why i always have an exception (can not find file) by your example? (we should put a @ sign befire "CMD..., am i right?) – SilverLight Sep 08 '12 at 21:18
2

A user doesn't have sufficient rights to delete files from c:\windows\system32 on Windows Vista and up. Even when logged-on using an administrator account. UAC puts a stop to it. You must ask for elevation to let the user know that you are about to tinker with the private parts. That requires embedding a manifest in your program to trigger the UAC prompt. This answer shows you how.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536