How can I get the location from which my program is running? - C #

-1

I would like to know how I can obtain the location from which my program is running.

For example: I created a text editor and I want that if I put my program to start by default in a txt file, that the program when opening it tells me the address where that txt file is located.

To put the program by default, I right click on the text file and in the properties I change the program with which the txt opens. But when I managed to do or that the program tells me the location of that txt I will do this process by executing a batch code to change the program by which programs with this extension are opened by default.

    
asked by Joaquin Giordano 30.04.2017 в 20:08
source

1 answer

0

You can know which is the path in which the context of the application is running by looking at BaseDirectory of AppDomain .

AppDomain.CurrentDomain.BaseDirectory

What you say about the file .txt I did not understand it very well, but if it is in the same directory as the .exe of the application, the case would be the same.

If not, to open it you need the path beforehand, so I'm not sure what would be the case that you need to control beyond the BaseDirectory .

EDITED: Based on the comments, I add this other answer to recover the path of the file.

When you create a file association in Windows, basically what you do is send it as an argument by command line.

To recover it, you simply have to recover that argument

static void Main(string[] args)
{
    IList<string> ficheros = new List<string>();
    foreach (string fichero in args)
    {
        ficheros.Add(fichero);
    }
}

With this code in the main main what we do is recover all the arguments that are passed to our executable (presumably file paths) and fill a list with these parameters.

If you only want to open a file every time and do not support opening several files at once, you simply need to recover the first parameter:

static void Main(string[] args)
{
    string fichero = null;
    if(args.Length > 0)
    {
        fichero = args[0];
    }
}
    
answered by 30.04.2017 / 20:10
source