2011-05-19 78 views
2

我需要確保我的WIDNOWS應用程序(WinForm的不是控制檯)在一定的用戶帳戶下運行(換句話說,任何用戶都可以到MACHING被記錄,但該.exe總會按指定的用戶執行)。運行Windows應用程序使用特定的用戶帳戶

可以這樣做程式設計?如果是這樣,怎麼樣?

+0

你如何意圖作爲用戶進行身份驗證?你會在什麼地方存儲密碼? – 2011-05-19 17:30:35

+0

是的,我可以將pwd存儲在應用可以訪問的地方。或者,如果需要,可以硬編碼。 – Robert 2011-05-20 04:58:59

回答

5

你可以這樣開始應用:

ProcessStartInfo psi = new ProcessStartInfo(myPath); 
psi.UserName = username; 

SecureString ss = new SecureString(); 
foreach (char c in password) 
{ 
ss.AppendChar(c); 
} 

psi.Password = ss; 
psi.UseShellExecute = false; 
Process.Start(psi); 
1

一件事,你可以在你的應用程序做的是檢查您是否爲所期望的用戶在運行,如果沒有,創建應用程序的新實例,爲其他用戶。第一例將退出。

檢查正在運行作爲用戶,你可以在解決方案從here適應,這樣的過程查詢本身的令牌信息。

使用CreateProcessWithLogonW,傳遞LOGON_WITH_PROFILE登錄標誌。您正在登錄的用戶必須設置適當的策略才能以交互方式登錄。

編輯:既然你已經表明你正在使用.NET,這裏是你應該怎麼做:

首先,你需要找出哪些用戶當前運行的。使用System.Security.Principal命名空間中的WindowsIdentity類。調用它的GetCurrent方法來獲取正在運行的用戶的WindowsIdentity對象。 Name屬性將爲您提供您正在運行的實際用戶名。

在你ProcessStartInfo對象,設置LoadUserProfile = true,在FileName場,可能是Arguments領域,UserNamePassword領域,可能是Domain場,並設置UseShellExecute = false。然後撥打Process.Start(),傳入您的ProcessStartInfo對象。

下面是我扔在一起的樣本,但我沒有安裝一個C#編譯器來測試它:

using System; 
using System.Diagnostics; 
using System.Security; 
using System.Security.Principal; 

// Suppose I need to run as user "foo" with password "bar" 

class TestApp 
{ 
    static void Main(string[] args) 
    { 
     string userName = WindowsIdentity.GetCurrent().Name; 
     if(!userName.Equals("foo")) { 
      ProcessStartInfo startInfo = new ProcessStartInfo(); 
      startInfo.FileName = "testapp.exe"; 
      startInfo.UserName = "foo"; 

      SecureString password = new SecureString(); 
      password.AppendChar('b'); 
      password.AppendChar('a'); 
      password.AppendChar('r'); 
      startInfo.Password = password; 

      startInfo.LoadUserProfile = true; 
      startInfo.UseShellExecute = false; 

      Process.Start(startInfo);  
      return; 
     } 
     // If we make it here then we're running as "foo" 
    } 
} 
+0

感謝您的鏈接。我正在使用C#,但會看看早上提出的解決方案。 – Robert 2011-05-20 04:59:30

+1

請參閱我的編輯,我添加了一些與.NET相關的內容。 – 2011-05-20 19:42:10

相關問題