Example #1
0
 internal static extern bool AdjustTokenPrivileges(SafeHandle TokenHandle,
     [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
     ref TOKEN_PRIVILEGES NewState,
     Int32 BufferLength,
     //ref TOKEN_PRIVILEGES PreviousState,					!! for some reason this won't accept null
     IntPtr PreviousState,
     IntPtr ReturnLength);
        public static SafeFileHandle GetHandle(this FileSystemInfo dir)
        {
            bool success;
            SafeHandleImpl token;
            TOKEN_PRIVILEGES tokenPrivileges = new TOKEN_PRIVILEGES();
            tokenPrivileges.Privileges = new LUID_AND_ATTRIBUTES[1];
            SafeHandle processHandle = Kernel32.GetCurrentProcess();
            success = Advapi32.OpenProcessToken(
                processHandle,
                Constants.TOKEN_ADJUST_PRIVILEGES,
                out token);

            if (success)
            {
                // null for local system

                success = Advapi32.LookupPrivilegeValue(null, Constants.SE_BACKUP_NAME,
                                               out tokenPrivileges.Privileges[0].Luid);
                if (success)
                {
                    tokenPrivileges.PrivilegeCount = 1;
                    tokenPrivileges.Privileges[0].Attributes = Constants.SE_PRIVILEGE_ENABLED;
                    success = Advapi32.AdjustTokenPrivileges(
                        token,
                        false,
                        ref tokenPrivileges,
                        Marshal.SizeOf(tokenPrivileges),
                        IntPtr.Zero,
                        IntPtr.Zero);
                }
                token.Close();
            }

            SafeFileHandle h = Kernel32.CreateFile(
                dir.FullName,
                Constants.GENERIC_WRITE,
                Constants.FILE_SHARE_READ | Constants.FILE_SHARE_WRITE,
                0,
                (uint)FileMode.Open,
                Constants.FILE_FLAG_BACKUP_SEMANTICS | Constants.FILE_FLAG_OPEN_REPARSE_POINT,
                (int)IntPtr.Zero
                );
            return h;
        }