c# 怎么获取当前登入的域账户
时间: 2024-04-22 09:22:50 浏览: 10
你可以使用 `System.DirectoryServices.AccountManagement` 命名空间下的 `UserPrincipal.Current` 属性来获取当前登录用户的信息,包括域账户和其他属性。使用此属性需要添加对 `System.DirectoryServices.AccountManagement` 的引用。以下是一个示例代码:
```csharp
using System.DirectoryServices.AccountManagement;
// 获取当前登录用户的信息
UserPrincipal user = UserPrincipal.Current;
// 输出用户的域账户名称
Console.WriteLine(user.SamAccountName);
```
注意,此方法只适用于在域环境中登录的用户。如果你是在本地计算机上登录的,此方法将无法获取到域账户信息。
相关问题
c# 获取当前时间戳
在C#中,可以使用DateTime类来获取当前时间戳。时间戳通常是指从某个特定时间(如1970年1月1日)到当前时间的总秒数或毫秒数。
以下是获取当前时间戳的几种常见方法:
1. 使用DateTime.Now属性获取当前时间,然后将其转换为Unix时间戳:
```csharp
DateTime now = DateTime.Now;
DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long timestamp = (long)(now.ToUniversalTime() - unixEpoch).TotalSeconds;
```
2. 使用DateTimeOffset类获取当前时间,并将其转换为Unix时间戳:
```csharp
DateTimeOffset now = DateTimeOffset.Now;
DateTimeOffset unixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
long timestamp = (long)(now - unixEpoch).TotalSeconds;
```
3. 使用TimeSpan类获取当前时间与Unix时间戳之间的差值:
```csharp
DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
TimeSpan timeSpan = DateTime.UtcNow - unixEpoch;
long timestamp = (long)timeSpan.TotalSeconds;
```
请注意,以上方法获取的是以秒为单位的时间戳。如果需要以毫秒为单位的时间戳,只需将`TotalSeconds`替换为`TotalMilliseconds`即可。
C# 获取当前时间戳
以下是两种C#获取当前时间戳的例子:
1.获取当前时间戳(秒)
```csharp
public string GetTimeStamp()
{
TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
```
2.获取当前时间戳(毫秒)
```csharp
public static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
```