C#: Check if administrator has write access to a file
Posted
by
Bilal Aslam
on Stack Overflow
See other posts from Stack Overflow
or by Bilal Aslam
Published on 2011-01-09T07:40:57Z
Indexed on
2011/01/09
7:53 UTC
Read the original article
Hit count: 293
The Problem:
I need to check if a user (local user or domain user, either one is possible) has write access to a file (if you're curious, %windir%\system32\inetsrv\applicationHost.config
. This file is protected by Windows and you need to be an administrator to write to it.)
My Solution: The general construct is:
using (Impersonator impersonator = new Impersonator(domain, username, password))
{
try
{
using (FileStream fs = File.OpenWrite(appHostConfigPath))
{
return true;
}
catch
{
return false;
}
}
As you can imagine, the Impersonator class is an IDisposible which uses native interop to call LogonUser. Nothing too creative, and it works.
Where I am stuck:
On Windows OSs with UAC enabled, this function always return false
even if the user specified by username is an administrator. Even though my program is running elevated as an administrator, I suspect what's happening is that the impersonated code is running as a limited administrator. Hence, the method is returning false.
I don't have any creative solutions to this. Can anyone help?
© Stack Overflow or respective owner