前天,在CodeProject看到一篇文章http://www.codeproject.com/KB/system/LSAEnumUserSessions.aspx
如何读取windows 当前登录用户的状态信息。
主要代码分享如下:
一:导入dll
二、调用方法,写入一个ListBox中
public
void
PopulateListbox()
{
System.Security.Principal.WindowsIdentity currentUser
=
System.Security.Principal.WindowsIdentity.GetCurrent();
DateTime systime
=
new
DateTime(
1601
,
1
,
1
,
0
,
0
,
0
,
0
);
//
win32 systemdate
UInt64 count;
IntPtr luidPtr
=
IntPtr.Zero;
LsaEnumerateLogonSessions(
out
count,
out
luidPtr);
//
gets an array of pointers to LUIDs
IntPtr iter
=
luidPtr;
//
set the pointer to the start of the array
for
(
ulong
i
=
0
; i
<
count; i
++
)
//
for each pointer in the array
{
IntPtr sessionData;
LsaGetLogonSessionData(iter,
out
sessionData);
SECURITY_LOGON_SESSION_DATA data
=
(SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(sessionData,
typeof
(SECURITY_LOGON_SESSION_DATA));
//
if we have a valid logon
if
(data.PSiD
!=
IntPtr.Zero)
{
//
get the security identifier for further use
System.Security.Principal.SecurityIdentifier sid
=
new
System.Security.Principal.SecurityIdentifier(data.PSiD);
//
extract some useful information from the session data struct
string
username
=
Marshal.PtrToStringUni(data.Username.buffer).Trim();
//
get the account username
string
domain
=
Marshal.PtrToStringUni(data.LoginDomain.buffer).Trim();
//
domain for this account
string
authpackage
=
Marshal.PtrToStringUni(data.AuthenticationPackage.buffer).Trim();
//
authentication package
SECURITY_LOGON_TYPE secType
=
(SECURITY_LOGON_TYPE)data.LogonType;
DateTime time
=
systime.AddTicks((
long
)data.LoginTime);
//
get the datetime the session was logged in
listBox1.Items.Add(
"
User:
"
+
username
+
"
*** Domain:
"
+
domain
+
"
*** Login Type: (
"
+
data.LogonType
+
"
)
"
+
secType.ToString()
+
"
*** Login Time:
"
+
time.ToLocalTime().ToString());
}
iter
=
(IntPtr)((
int
)iter
+
Marshal.SizeOf(
typeof
(LUID)));
//
move the pointer forward
LsaFreeReturnBuffer(sessionData);
//
free the SECURITY_LOGON_SESSION_DATA memory in the struct
}
LsaFreeReturnBuffer(luidPtr);
//
free the array of LUIDs
}
更多DirectoryEntry的信息,请查阅
http://msdn.microsoft.com/zh-cn/library/system.directoryservices.directoryentry_members.aspx