Skip to content

GetLoggedUserName returns empty string on WSL (include possible fix) #127

Open
@vesnx

Description

@vesnx

I tested the GetLoggedUserName and found that it is possebly not implemented the right way as for me getlogin reurns a $0000000000000000 (empty string)

I left the original code , removed the cast error for UTF8ToString and look at the "GetEnvironmentVariable" for USER or LOGINNAME

This seems to reflect my user name on all system WSL, VM or physical

Perhaps you consider it in your update

function GetLoggedUserName: string;
{$IFDEF MSWINDOWS}
const
  cnMaxUserNameLen = 254;
var
  sUserName: string;
  dwUserNameLen: DWORD;
begin
  dwUserNameLen := cnMaxUserNameLen - 1;
  SetLength(sUserName, cnMaxUserNameLen);
  GetUserName(PChar(sUserName), dwUserNameLen);
  SetLength(sUserName, dwUserNameLen);
  Result := sUserName;
end;
{$ELSE}
{$IF DEFINED(FPC) AND DEFINED(LINUX)}

begin
  Result := GetEnvironmentVariable('USERNAME');
end;
{$ELSE}

var
{$IFNDEF NEXTGEN}
  plogin: PAnsiChar;
{$ELSE}
  plogin: MarshaledAString;
{$ENDIF}
begin
{$IFDEF POSIX}
  try
    plogin := getlogin;
{$IFDEF NEXTGEN}
    Result := string(plogin);
    // NEXTGEN platforms handle strings differently, so direct assignment might be fine.
{$ELSE}
    if Length(plogin) > 0 then
    begin
      // Assuming UTF-8 encoding for plogin. If the encoding is different, adjust accordingly.
      Result := UTF8ToString(plogin);
      // Correct way to convert UTF-8 encoded PAnsiChar to UnicodeString
    end
    else
    begin
      if GetEnvironmentVariable('USER') <> '' then
      begin
        Result := GetEnvironmentVariable('USER');
      end
      else if GetEnvironmentVariable('LOGNAME') <> '' then
      begin
        Result := GetEnvironmentVariable('LOGNAME');
      end;

    end;

{$ENDIF}
  except
    Result := 'N/A';
  end;
{$ELSE}
  Result := 'N/A';
{$ENDIF}
  // raise ENotImplemented.Create('Not Android GetLoggedUserName implemented!');
end;
{$ENDIF}
{$ENDIF}
{$IFDEF IOS}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions