2

I've tried to create a Console Application program, and cause the application to run on startup. I found some solutions, but they uses external dll files (Of the operation system, in my case - Windows) or they refers to Windows Forms / WPF. I've realized that the startup code for Windows Forms application is pretty different than from a Console Application's startup code.. Can Someone help me? I really confused now..

Here's the code I found: (on this url: How to run a C# application at Windows startup?)

RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());

How can I do this action for a console application, with code that will be similar to this one, and without using external dlls?

Thanks..

Community
  • 1
  • 1
Aviv
  • 456
  • 1
  • 7
  • 16

2 Answers2

4

Application.ExecutablePath is only used by Windows apps. To get the executing assembly of any app, use Assembly.GetExecutingAssembly().Location:

RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Assembly.GetExecutingAssembly().Location);
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • will this work for other platforms like macos and linux. I want my console app to be started automatically like we do on windows startup apps. – Thameem Oct 22 '22 at 05:22
2

You've already got the right solution. The Registry classes in the .NET framework don't require WinForms or WPF references, so you're free to use them in a console application without littering your project with unnecessary references.

Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
  • but when i'm trying to use this in my code, it gives me an error in the part "Application.ExecutablePath.ToString()" in the second line.. why is this happening? – Aviv Jun 26 '13 at 17:09
  • 1
    @Aviv you never mention that in your original question, edit your question and please include that information and what the error says in your post. – Scott Chamberlain Jun 26 '13 at 17:18
  • Try Assembly.GetEntryAssembly() instead – V Maharajh Jun 26 '13 at 17:19