大家好!
小弟碰到一个问题;
由于在user用户组中的用户,在c:\program files文件下面的所有文件夹都是只读的,
而现在小弟做了一个软件,需要在它下面产生一个临时文件,但执行都“拒绝访问”;请问各位有没方法,在程序里控制“c:\program files\xx_tmp”文件夹可以进行文件读写的方法

解决方案 »

  1.   

    public const int LOGON32_LOGON_INTERACTIVE = 2;  //有的时候要改成9才好使用,
    public const int LOGON32_PROVIDER_DEFAULT = 0;WindowsImpersonationContext impersonationContext; [DllImport("advapi32.dll", CharSet=CharSet.Auto)]
    public static extern int LogonUser(String lpszUserName, 
                                      String lpszDomain,
                                      String lpszPassword,
                                      int dwLogonType, 
                                      int dwLogonProvider,
                                      ref IntPtr phToken);
    [DllImport("advapi32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
    public extern static int DuplicateToken(IntPtr hToken, 
                                      int impersonationLevel,  
                                      ref IntPtr hNewToken);public void 你的函数啦啦啦~~~~()
    {
        //使用有权限用户,域名(工作组中是机器名),密码模拟用户
       if(impersonateValidUser("username", "domain", "password"))
       {
          //在这里执行你的写操作      undoImpersonation(); // 结束身份模拟
       }
       else
       {
          //发生异常 身份模拟失败了
       }
    }private bool impersonateValidUser(String userName, String domain, String password)
    {
       WindowsIdentity tempWindowsIdentity;
       IntPtr token = IntPtr.Zero;
       IntPtr tokenDuplicate = IntPtr.Zero;   if(LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, 
       LOGON32_PROVIDER_DEFAULT, ref token) != 0)
       {
          if(DuplicateToken(token, 2, ref tokenDuplicate) != 0) 
          {
             tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
             impersonationContext = tempWindowsIdentity.Impersonate();
             if (impersonationContext != null)
                return true;
             else
                return false; 
          }
          else
             return false;
       } 
       else
          return false;
    }
    private void undoImpersonation()
    {
         impersonationContext.Undo();

      

  2.   

    System.IO.Directory.Create("C:\\program files\\xx_tmp");
    然后就可以对xx_tmp进行write操作了
      

  3.   

    就是模拟一个有权限的用户.文件夹->右键->属性->安全