tags:

views:

166

answers:

3

for delphi I want to learn if my application has admin rights, is there a solution for this you may know ?

related question:

http://stackoverflow.com/questions/3300023/how-to-launch-an-application-with-admin-rights

A: 

As to knowing wether or not your program has admin rights, I have no code for that, but This might be an idea. Note that I just wrote it and is untested.

But the idea is if you are able to create a file at the program files folder then you probably have admin rights.

function IsRunningWithAdminPrivs: Boolean;
begin
var
  List: TStringList;
begin
  List := TStringList.Create;
  try
    try
      List.Text := 'Sample';
      // Use SHGetFolder path to retreive the program files folder
      // here is hardcoded for the sake of the example
      List.SaveToFile('C:\program files\test.txt');
      Result := True;
    except
      Result := False;
    end;
  finally
    List.Free;
    DeleteFile('C:\program files\test.txt');
  end;
end;
Aldo
why not probe current privileges by overwriting random partition table?
This only tests if you can write to 'program files' directory, and would fail if the security settings of the directory have been changed accordingly... And also it will always return true because of a bug in the code (`result := true` in finally). ;)
Sertac Akyuz
This will fail in lots of ways. On many versions of localized windows C:\Program Files is not always using that name. You should never ever hard-code a system path into your code. Use the APIs.
Warren P
Edited the comment to fix the bug always returning true, and for Warren, as you could have read in the function body, I was suggesting to use the appropriate API to find the folder path, and used a hard-coded string just for the sake of the example.
Aldo
I think DeleteFiles will also possibly raise an unhandled exception if it fails (ie the test file was never deleted).
Warren P
I think that it won't, it will simply return false
Aldo
Aside from the fact that this function *doesn't actually test whether the app is running elevated* (exercise: why?), it would also do bad things if the user had an existing `test.txt`.
Craig Stuntz
+4  A: 

You call the WinAPI function GetTokenInformation, passing TokenElevation. There's a C++ example here which should be easy to convert.

Note that being the administrator and being elevated are different.

Craig Stuntz
A: 

Just attempt to do something that requires administrative privileges:

uses
  WinSvc;

function IsAdmin(Host : string = '') : Boolean;
var
  H: SC_HANDLE;
begin
  if Win32Platform <> VER_PLATFORM_WIN32_NT then
    Result := True
  else begin
    H := OpenSCManager(PChar(Host), nil, GENERIC_READ or GENERIC_WRITE or GENERIC_EXECUTE);
    Result := H <> 0;
    if Result then
      CloseServiceHandle(H);
  end;
end;
davea