Bob Bryan
Bob Bryan

Reputation: 3837

How to access the Application object from a console app?

I took some code from my C# Windows form app which uses the Application object to get the start up path and tried to use it in a console app. When I did this, the compiler displayed the following error msg - "The name 'Applicaiton' does not exist in the current context. Did some research and discovered that the Application object is in System.Windows.Forms namespace. So, I added a reference to this with no apparent effect. Then, tried adding using System.Windows.Forms to the top of the file and got a new error message - "The type or namespace name 'Windows' does not exist in the namespace 'System' (are you missing an assembly reference?)." Can anyone shed some light on how to access the Application object from a console app?

Upvotes: 4

Views: 6193

Answers (4)

Denis Biondic
Denis Biondic

Reputation: 8201

System.Reflection.Assembly.GetExecutingAssembly().Location

Also, of directory needed, wrap the call in System.IO.Path.GetDirectory()

Upvotes: 6

Bueller
Bueller

Reputation: 2344

The metod offered by Denis Biondic is the right way to go for a console application. But in answer to your question you could do it that way if you added a reference to System.Windows in the references to your application. When you select a console application template, that reference is not included by default so if you need members from that namespace you have to add a reference to the dll.

Upvotes: 0

Waleed
Waleed

Reputation: 3145

Application is not available for Console Applications, it's for windows forms. You can use

Assembly.GetExecutingAssembly().CodeBase

Upvotes: 2

Petar Ivanov
Petar Ivanov

Reputation: 93030

You need to both add reference to the System.Windows.Forms (right click on References and 'Add Reference...') and add using System.Windows.Forms at the top of your file. It worked for me.

Upvotes: 1

Related Questions