C# 获取windows当前登录用户信息
时间: 2023-08-18 13:36:40 浏览: 151
您可以使用以下代码来获取当前登录的Windows用户信息:
```
using System.Security.Principal;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
string username = identity.Name;
SecurityIdentifier sid = identity.User;
string userSid = sid.Value;
```
其中,`username` 变量将包含当前登录用户的用户名,`userSid` 变量将包含当前登录用户的安全标识符(SID)。请注意,您需要在代码中添加 `using System.Security.Principal;` 引用才能使用 `WindowsIdentity` 和 `SecurityIdentifier` 类。
相关问题
C# 获取windows当前IP地址
可以使用以下代码来获取Windows当前IP地址:
```csharp
using System.Net;
using System.Net.Sockets;
public static string GetLocalIPAddress()
{
string ipAddress = "";
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = ip.ToString();
break;
}
}
return ipAddress;
}
```
此代码将返回Windows当前使用的IPv4地址。
C# 获取windows当前ip地址与mac
可以使用以下代码获取Windows当前IP地址和MAC地址:
```csharp
using System.Net;
using System.Net.NetworkInformation;
using System.Linq;
public static string GetLocalIPAddress()
{
string ipAddress = "";
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = ip.ToString();
break;
}
}
return ipAddress;
}
public static string GetMacAddress()
{
string macAddress = "";
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.OperationalStatus == OperationalStatus.Up && adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
macAddress = string.Join(":", (from z in adapter.GetPhysicalAddress().GetAddressBytes() select z.ToString("X2")).ToArray());
break;
}
}
return macAddress;
}
```
上述代码中,GetLocalIPAddress()函数将返回Windows当前使用的IPv4地址,而GetMacAddress()函数将返回Windows当前使用的MAC地址。请注意,如果存在多个活动网络适配器,则GetMacAddress()函数返回的是第一个不是环回适配器的MAC地址。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)