Question

I wanted to add my C# application to Windows autorun programmatically and read somewhere that code below would do the trick:

var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("MyApplication", System.Reflection.Assembly.GetEntryAssembly().Location);

When I restarted my computer, application's splash screen showed up but after a few seconds the application crashed and I saw this:

an unhandled microsoft .net framework exception occured 

Could you give me some clues where to look for source of the problem?

EDIT : I ran debugger and that's what I found out (XamlParseException):

{"'The invocation of the constructor on type 'MyApplication.GUI.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'."}

And inner exception message (System.UnauthorizedAccessException):

{"Access to the path 'C:\\Windows\\system32\\db.db' is denied."}
Was it helpful?

Solution

This is a bug in your code, you are using a relative filename instead of a full path. In other words, "db.db" instead of "c:\foo\bar\db.db". You'll now have a big dependency on the default directory of the program. This will work just fine in Visual Studio when you debug and test your app, the default directory will be the bin\debug directory of your project. You'll have no trouble writing to that directory.

But will not work when your program is launched by Windows, the default directory of your program will now be the default Windows directory, c:\windows\system32. Programs do not have write access to that directory, it is protected by UAC.

Fix the bug by specifying the full path to the file. You'll want to use Environment.GetFolderPath() to obtain a good directory, that should almost always be SpecialFolder.ApplicationData. Use the Path.Combine() helper method to construct the path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top