我生如山

[C#学习笔记]在Vista或者Server2008下以Admin模式启动程序

原文(参考文章)链接:http://www.codeproject.com/KB/vista-security/UAC_Shield_for_Elevation.aspx

Vista和Windows Server 2008上面系统的UAC(User Account Control)默认是开启的,用户在一般情况下并通过双击启动程序都不是以管理员模式运行。但是,在很多情况下,为了在程序里面访问系统的某些特定资源,需要当前程序的identity具有admin的权限。那么这就需要涉及到检测当前程序的执行用户是否处于管理员模式,在当前程序不处于admin模式的情况以admin模式下重启程序。

参考了http://www.codeproject.com/KB/vista-security/UAC_Shield_for_Elevation.aspx这篇文章,做如下学习笔记。

为了检测当前进程的之行用户是否是管理员,需要用到CLR种System.Security.Principal名称空间种的WindowsIdentity类和WindowsPrincipal类。下面是代码,很好理解:

static bool IsAdmin()
        
{
            WindowsIdentity identity 
= WindowsIdentity.GetCurrent();
            WindowsPrincipal principle 
= new WindowsPrincipal(identity);
            
return principle.IsInRole(WindowsBuiltInRole.Administrator);
        }

如果当前进程不是处于管理员模式,那么我们可以重启这个程序。为了重启程序使用了System.Diagnostics名称空间下的Process类,Process类调用命令行下的"runas"命令,以管理员模式重新启动当前程序。代码如下,也很好理解:

 static void RestartProcessElevated()
        
{
            ProcessStartInfo info 
= new ProcessStartInfo();
            info.UseShellExecute 
= true;
            info.WorkingDirectory 
= Environment.CurrentDirectory;
            info.FileName 
= System.Windows.Forms.Application.ExecutablePath;
            info.Verb 
= "runas";
            
try
            
{
                Process.Start(info);
            }

            
catch (System.ComponentModel.Win32Exception ex)
            
{
                Console.WriteLine(
"Exception:{0}", ex.Message);
                
return;
            }


            System.Windows.Forms.Application.Exit();
        }

posted on 2009-05-22 18:36 悟山 阅读(339) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理