2

I want to get windows user's profile name from my Flutter desktop app. Is there a way to get it?

aoiTenshi
  • 547
  • 1
  • 6
  • 20

1 Answers1

2

The win32 method for this is GetUserName. Rather than go through the trouble of setting up a plugin with a method channel, we can call this directly with ffi. You'll need the ffi and win32 packages.

import 'dart:ffi';

import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';

// This is the max win32 username length. It is missing from the win32 package,
// so we'll just create our own constant.
const unLen = 256;

String getUsername() {
  return using<String>((arena) {
    final buffer = arena.allocate<Utf16>(sizeOf<Uint16>() * (unLen + 1));
    final bufferSize = arena.allocate<Uint32>(sizeOf<Uint32>());
    bufferSize.value = unLen + 1;
    final result = GetUserName(buffer, bufferSize);
    if (result == 0) {
      GetLastError();
      throw Exception(
          'Failed to get win32 username: error 0x${result.toRadixString(16)}');
    }
    return buffer.toDartString();
  });
}
jmatth
  • 216
  • 2
  • 6
  • Does it also work for x64 if I only change x32 parameters to x64 ones? – aoiTenshi Oct 07 '22 at 08:38
  • As far as I know none of this depends on the architecture. I tested it on a 64 bit Windows 11 machine. What part do you think is architecture-specific? – jmatth Oct 07 '22 at 14:01
  • I thought about username length and uint. – aoiTenshi Oct 07 '22 at 15:07
  • 1
    The function uses a uint32 regardless of processor architecture. I can't find any alternate versions of the header file with a larger value of `UN_LEN`. It you want to be paranoid you could allocate more bytes in case Microsoft increases the max length of usernames in the future. Personally I wouldn't bother but an extra kb or so of ram that gets used for one call and instantly freed isn't likely to cause issues on any modern system. – jmatth Oct 07 '22 at 21:32