How to take the path of the open executable in C#

Asked

Viewed 19,154 times

5

How do I take the path of the project in c#?
Is there any function?
Or I have to write the full path on my application?

  • When do you want to search for this information? 1) Script execution (Runtime)? 2) During Build (build)?

  • Exact... At the moment you are running. Because I want to know where my project is so that later I can execute a routine of my own, in which I would save a file in a subfolder of the project.

  • 2

    OK, just for definition: 'Project' != 'Executable'. The answer given by @Isalamon should resolve your question.

3 answers

8


Use :

String path = System.AppDomain.CurrentDomain.BaseDirectory.ToString();

To create a sub folder you can do so:

class Program
{
    static void Main(string[] args)
    {

        string path = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
        //
        string path2 = path.Remove(path.LastIndexOf("\\"));
        path = path2.Remove(path2.LastIndexOf("\\") + 1);
        path += "log";

        System.IO.Directory.CreateDirectory(path);

    }
}

EDIT

Reviewing a code I found another implementation that does the same thing:

string curDir = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory.ToString());

Then just mount the string with the path you want to create. If you are on the same level batsa do the following :

string new_dir = curDir + "\\..\\log";

System.IO.Directory.Createdirectory(new_dir);

Don’t forget to make all your consistencies.

  • This shows the path to the open executable, not the .csproj. file path..

  • 1

    I voted against at the beginning, but to see the comment of the PO on need to know the way of executable, I removed the negative vote and now add a positive.

2

If you want the program execution path:

System.Environment.CurrentDirectory

1

The method reported by @Isalamon is correct. But it’s also possible to search for Assembly:

String currentPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Models.Configuracao)).Location);

Where it appears Models. just replace it with the name of the Assembly you want to find the path.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.