I have written a wrapper application in .Net that starts another WinForms application with a specified user name and password. For the background behind why I am needing to do this, you can look at the following question that I posted earlier this week:
Here is the code for the wrapper application:
string sysFolder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
ProcessStartInfo pInfo = new ProcessStartInfo();
pInfo.FileName = (sysFolder + @"\AppMain.exe").Replace(@"file:\", @"\\");
pInfo.UserName = GetUserName();
pInfo.Password = ToSecure(GetPassword());
pInfo.UseShellExecute = false;
Process p = Process.Start(pInfo);
p.WaitForExit();
The methods GetUserName() and GetPassword() simply retrieve the user name and password from an encrypted text file. The method ToSecure() just converts a String to a System.Security.SecureString.
Ok. Now here is the weird part! 🙂 This wrapper application actually works correctly MOST of the time; but for some strange reason it seems to run into a problem right after a system restart. After a restart, for about 5 minutes the application that is being launched (AppMain.exe), throws a UnauthorizedAccessException when the application tries to write to the windows registry. I have no idea why this is only going wrong in the first 5 minutes and then suddenly starts working correctly.
Note also that I have to close the application and restart it after five minutes into the boot for it to work correctly. If I just press “continue” on the expection, it keeps giving the execption when attempting to write to the registry.
Here is the code that will throw the exception when the application is started after a reboot.
Microsoft.VisualBasic.Interaction.SaveSetting("app", "settings", "time", DateTime.Now.ToString());
I have confirmed this behaviour on XP and on Windows 7. Anyone have any idea why this is happening at startup and why the exception suddenly goes away if I launch the application after 5 minutes into the boot.
I have finally discovered what is causing this problem. I found the answer here:
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.loaduserprofile.aspx
ProcessStartInfo.LoadUserProfile was the missing piece to the puzzle. In the process information object there is a property LoadUserProfile which indicates if the user’s profile must be loaded, and the default value for this property is false. But if the process that you are calling is needing to access HKEY_CURRENT_USER as my called process was trying to do, then this property must be set to true.
So once I set LoadUserProfile to true in pInfo then my application worked 100%, even directly after a restart.