C # - Path to execution

4

I am doing a launcher, however I would like to leave the files with a "fixed" path, the launcher is in the same folder as the file to be started, but I do not know how I could create a "midway", something like in html, that just put a piece of the path, if it is in the same folder, as is the case.

I'm using forms, .NET 3.5.

The folders look like this: folder x / folder launcher / ...
folder x / folder prog /...

    
asked by anonymous 01.03.2014 / 17:10

2 answers

2

In C #, you can get the path to the program executable to be executed.

string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);

Where Assembly is in the namespace System.Reflection .

This gives us the path to the launcher executable . But this is not what is intended. If the launcher is "C: / x folder / launcher folder / launcher.exe", we want to have the path to "C: / folder x / folder prog /".

string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string launcherPath = Uri.UnescapeDataString(uri.Path); //launcher.exe
string launcherDir = Path.GetDirectoryName(launcherPath); //pasta launcher
string appDir = Path.GetDirectoryName(launcherDir); //pasta x
string programPath = Path.Combine(appDir, "pasta prog", "program.exe");

Path belongs to the namespace System.IO . With this code, we get the path to the program to run in the programPath variable.

But there is a simpler way to get relative paths. For this, we will combine the methods Path.Combine and Path.GetFullPath .

        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string launcherPath = Uri.UnescapeDataString(uri.Path);
        string programPath = Path.GetFullPath(Path.Combine(launcherPath, "../../pasta prog/program.exe"));
    
03.03.2014 / 00:33
1

The name of this is not "fixed path" but rather "relative path" ... but I think I understand what you mean, actually the string is fixed, representing a path relative. =)

I do not see problems using a relative path ... I just tested and it works perfectly:

var proc = Process.Start(@"..\pasta prog\nomeDoPrograma.exe");

Attention to creating a launcher shortcut

Note that the relative path is resolved relative to the path indicated in Environment.CurrentDirectory . If you create a shortcut to the launcher, the property that indicates the start path will be passed to this .Net environment variable.

    
01.03.2014 / 18:43