Reputation: 20468
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?
Upvotes: 0
Views: 10680
Reputation: 6471
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.
Upvotes: 2
Reputation: 941744
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.
Upvotes: 2