.Net应用程序在多用户环境中访问Outlook

时间:2015-09-07 01:48:02

标签: .net citrix

我有一个在Citrix环境中运行的.net应用程序,此应用程序通过outlook发送电子邮件,只创建一个新实例(如果尚未运行) 然而,它偶尔会获得另一个用户的前景并尝试发送。

如何获取Outlook的当前用户进程?

1 个答案:

答案 0 :(得分:0)

您可以使用WMI查询来按名称获取进程列表。然后返回的Win32_Process对象包含GetOwner方法。

此示例将该信息存储在名为OwnedProcess的小类中,然后返回实际的Process对象供您使用。请注意,它确实返回First()匹配;假设你不关心你选择哪个Outlook实例,只要它在正确的用户下运行。

public class OwnedProcess
{
    public string Name { get; set; }
    public int Id { get; set; }
    public string Owner { get; set; }

    public static Process GetProcessByOwner(string ProcessName, string Username)
    {
        OwnedProcess result;

        ManagementScope scope = new ManagementScope(@"\\localhost\root\cimv2");
        SelectQuery query = new SelectQuery("SELECT * FROM Win32_Process WHERE Name = '" + ProcessName + "'");

        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
        {
            ManagementObjectCollection collection = searcher.Get();

            IEnumerable<OwnedProcess> processes = BuildProcesses(collection);

            result = processes.Where(p => p.Owner.Equals(Username)).First();
        }

        Process processResult = Process.GetProcessById(result.Id);

        return processResult;
    }

    private static IEnumerable<OwnedProcess> BuildProcesses(ManagementObjectCollection WmiResults)
    {
        foreach (ManagementObject result in WmiResults)
        {
            string[] ownerName = new string[2];
            result.InvokeMethod("GetOwner", ownerName);

            yield return
                new OwnedProcess
                {
                    Id = Convert.ToInt32(result["ProcessId"]),
                    Name = result["Name"].ToString(),
                    Owner = ownerName[0]
                };
        }
    }
}

然后可以这样调用:

string runningAs = Environment.UserName;
Process p = OwnedProcess.GetProcessByOwner("outlook.exe", runningAs);