开发者

C#: Check if administrator has write access to a file

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\config\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?


Could you look at the exception? Is it with the permissions or "File not found exception"? Because on Windows 7 it is at

%windir%\System32\inetsrv\config\applicationHost.config

may be the same with Windows Vista too.


How about GetFileSecurity and GetEffectiveRightsFromAcl?

The second link has an example which is actually quite complete (in C++).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜