开发者

C# Get user picture (Avatar)

开发者 https://www.devze.com 2023-04-01 09:13 出处:网络
I\'m referring to C# - How开发者_如何学运维 to get current user picture but I never found a solution. (I\'m working on Win7 OS)

I'm referring to C# - How开发者_如何学运维 to get current user picture but I never found a solution. (I'm working on Win7 OS)

For some users, the picture is located on

C:\Users\UserName\AppData\Local\Temp\UserName.bmp

(where UserName is user nickname) for others users this path throws FileNotFoundException but pictures exists.

Where I can find information about the path or real picture? There is a registry that contains this information?


This blog post shows how to set the user tile (picture). In a comment near the end (Michael Anthony, Apr 10, 22:45), the commenter describes how to get the picture. I've gathered the info into a C# snippet. Remember that this is based on an undocumented Windows Shell function.

    using System;
    using System.Text;
    using System.Drawing;

    [DllImport("shell32.dll", EntryPoint = "#261", 
               CharSet = CharSet.Unicode, PreserveSig = false)]
    public static extern void GetUserTilePath(
      string username, 
      UInt32 whatever, // 0x80000000
      StringBuilder picpath, int maxLength);

    public static string GetUserTilePath(string username)
    {   // username: use null for current user
        var sb = new StringBuilder(1000);
        GetUserTilePath(username, 0x80000000, sb, sb.Capacity);
        return sb.ToString();
    }

    public static Image GetUserTile(string username)
    {
        return Image.FromFile(GetUserTilePath(username));
    }

Note that this Shell function creates the file \Users\<USER>\AppData...\<USER>.bmp and returns its filename.

Also, I've tested it on Win7. I have no idea of its compatibility with former Windows versions.

Credits to Joco and Michael Anthony.


I have found relevant information at \HKEY_CURRENT_USER\Volatile Envirnment, but not the exact path.

My guess is that the avatar is always at C:\Users\UserName\AppData\Local\Temp\ and the file name itself can be found from this algorithm:

// Note that $XYZ$ means \HKEY_CURRENT_USER\Volatile Envirnment\XYZ
if $USERDOMAIN$ = "" then
    return $USERNAME$.Substring(0, $USERNAME$.IndexOf('.'));
else
    return $USERDOMAIN$ + "+" + $USERNAME$.Substring(0, $USERNAME$.IndexOf('.'));

Again, just a guess.

P.S.: There is Volatile Environment for all users, if you look at \HKEY_USERS. If you want a specific user, iterate over all users and check in the Volatile Environment for the user name (the sub-keys of \HKEY_USERS are just random strings, so you must look inside).

0

精彩评论

暂无评论...
验证码 换一张
取 消