获取系统当前用户登录名的问题
在XP及以后的Windows系统中,在启动可执行程序时,可以选择使用其他用户的身份启动。现在有一个问题,如何在程序启动后,在程序中获得当前系统的用户名,而不是启动程序时的用户名?例如:当前系统有两个用户a和b。登录a,并启动一个程序aaa.exe。启动时,选择使用b用户运行该程序。那么在程序中该如何进行判断,得到当前系统用户为a而不是b? --------------------编程问答-------------------- get hostname --------------------编程问答-------------------- using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsApplication25
{
public partial class Form1 : Form
{
[DllImport("Advapi32.dll", EntryPoint = "GetUserName",
ExactSpelling = false, SetLastError = true)]
static extern bool GetUserName(
[MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
[MarshalAs(UnmanagedType.LPArray)] Int32[] nSize);
public Form1()
{
InitializeComponent();
System.Text.StringBuilder b = new System.Text.StringBuilder(100);
int n = b.Capacity;
byte[] str = new byte[256];
Int32[] len = new Int32[1];
len[0] = 256;
GetUserName(str, len);
MessageBox.Show(System.Text.Encoding.ASCII.GetString(str));
string a;
a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
MessageBox.Show(a.ToString());
}
}
} --------------------编程问答-------------------- The GetUserName function retrieves the name of the user associated with the current thread.(MSDN)
所以,jinjazz(近身剪) 提出的解决方案应该够呛。 --------------------编程问答-------------------- 实际上,程序要求是这样的。
每个用户都有一个对应的数据目录。例如,在XP系统下,一般是C:\Document and Settings\<username>。
实际上问题想得到的结果是,在用户 UserA 登录系统后,使用用户 UserB 的身份启动程序pro.exe。那么使用什么方法,在程序pro.exe中,仍旧得到C:\Document and Settings\UserA这个目录,而不是C:\Document and Settings\UserB这个目录? --------------------编程问答-------------------- 已解决,封帖
补充:.NET技术 , .NET Framework