.NET 2.0 Process Impersonation feature not working in Windows App

.NET 2.0 introduced an interesting feature in the “Process”
class where you can specify UserName, Password and it runs the
process as the specified user. However, it only works inside
Console Application. It does not run if the application is a
Windows Application. It throws “Win32Exception Access Denied” when
the Start() is called. Is it as designed? I really need this
feature in a windows service.

Try the following code in a console app, it will run perfectly.
But change the application type to “Windows Application” and
run, it will throw exception. IF you do not set the UserName,
Password, it will run then. I am using VS 2005 Release
Candidate.

Here’s the code:

ProcessStartInfo startInfo = new
ProcessStartInfo(@”SampleEXE.exe”);

startInfo.Domain = “.”;

startInfo.UserName = “test”;

// create a secure string from the password we have

SecureString securePassword = new SecureString();

foreach (char c in “test”)

securePassword.AppendChar(c);

securePassword.MakeReadOnly();

startInfo.Password = securePassword;

startInfo.UseShellExecute = false;

startInfo.RedirectStandardOutput = true;

startInfo.RedirectStandardError = true;

startInfo.RedirectStandardInput = false;

startInfo.CreateNoWindow = true;

startInfo.WindowStyle = ProcessWindowStyle.Hidden;

startInfo.WorkingDirectory =

Path.GetDirectoryName(startInfo.FileName);

startInfo.Arguments = “Hi Hello How are you?”;

using (Process p = new Process())

{

p.StartInfo = startInfo;

p.Start();

string fileName = @”output.txt”;

using (StreamWriter writer = new StreamWriter(fileName))

{

writer.Write(p.StandardOutput.ReadToEnd());

writer.Close();

}

p.WaitForExit();

p.Close();

}