tags:

views:

52

answers:

3

Imagine I have a picture viewer application made with C# and .NET. I have already set the preferred application to view pictures to use the C# application.

I want to somehow let my program know where it has been invoked. How can I achieve this?

A: 

I think you can use Environment.CurrentDirectory

Gregoire
+3  A: 

If you're using it to view pictures via shell associations, you can just check the picture filenames passed in on the command line. You can use Environment.GetCommandLineArgs to get the first filename:

  // Should check to make sure there is at least one filename passed first...
  string imageFilename = Environment.GetCommandLineArgs[1];
  string directory = System.IO.Path.GetDirectoryName(imageFilename);

If you want the working directory, just check Environment.CurrentDirectory at startup...

Reed Copsey
A: 

The current directory (Environment.CurrentDirectory) of an application can change during execution. Additionally, the current directory may not be the directory in which the application resides, such as if a user runs it from a command line in an arbitrary directory by specifying an absolute path to the executable.

If you really want the "current directory" of the application, then use Environment.CurrentDirectory, but if you want to know the location of the application, you can use the following approaches:

  • System.Windows.Forms.Application.ExecutablePath (if running a WinForm application)

  • System.Windows.Forms.Application.StartupPath (if running a WinForm application)

  • System.Reflection.Assembly.GetEntryAssembly().Location

Dr. Wily's Apprentice