.gif)
.net读取Windows登录用户信息(downmoon)
前天,在CodeProject看到一篇文章http://www.codeproject.com/KB/system/LSAEnumUserSessions.aspx
如何读取windows 当前登录用户的状态信息。
主要代码分享如下:
一:导入dll

Code

/**//************************************************************************/

/**//* The following Interop code should be placed in a sealed internal NativeMethod class
* but has been left here to simplify the example.
/************************************************************************/

[DllImport("secur32.dll", SetLastError = false)]
private static extern uint LsaFreeReturnBuffer(IntPtr buffer);

[DllImport("Secur32.dll", SetLastError = false)]
private static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);

[DllImport("Secur32.dll", SetLastError = false)]
private static extern uint LsaGetLogonSessionData(IntPtr luid, out IntPtr ppLogonSessionData);

[StructLayout(LayoutKind.Sequential)]
private struct LSA_UNICODE_STRING

{
public UInt16 Length;
public UInt16 MaximumLength;
public IntPtr buffer;
}

[StructLayout(LayoutKind.Sequential)]
private struct LUID

{
public UInt32 LowPart;
public UInt32 HighPart;
}

[StructLayout(LayoutKind.Sequential)]
private struct SECURITY_LOGON_SESSION_DATA

{
public UInt32 Size;
public LUID LoginID;
public LSA_UNICODE_STRING Username;
public LSA_UNICODE_STRING LoginDomain;
public LSA_UNICODE_STRING AuthenticationPackage;
public UInt32 LogonType;
public UInt32 Session;
public IntPtr PSiD;
public UInt64 LoginTime;
public LSA_UNICODE_STRING LogonServer;
public LSA_UNICODE_STRING DnsDomainName;
public LSA_UNICODE_STRING Upn;
}

private enum SECURITY_LOGON_TYPE : uint

{
Interactive = 2, //The security principal is logging on interactively.
Network, //The security principal is logging using a network.
Batch, //The logon is for a batch process.
Service, //The logon is for a service account.
Proxy, //Not supported.
Unlock, //The logon is an attempt to unlock a workstation.
NetworkCleartext, //The logon is a network logon with cleartext credentials.
NewCredentials, // Allows the caller to clone its current token and specify new credentials for outbound connections. The new logon session has the same local identity but uses different credentials for other network connections.
RemoteInteractive, // A terminal server session that is both remote and interactive.
CachedInteractive, // Attempt to use the cached credentials without going out across the network.
CachedRemoteInteractive, // Same as RemoteInteractive, except used internally for auditing purposes.
CachedUnlock // The logon is an attempt to unlock a workstation.
}

二、调用方法,写入一个ListBox中

Code
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2007-12-30 GridView如何更新批量数据和单条记录?
2007-12-30 DeepClone与ShadowClone
2007-12-30 sql server 2005下奇怪的Delete Top 语句
2007-12-30 asp.net中url地址传送中文参数时的两种解决方案
2007-12-30 在GridView中如何格式化Money型字段?
2007-12-30 利用SoapHeader验证web service调用的合法性
2007-12-30 根据SQL存储过程名取得存储过程内容