How to Get the Directory That a Program Is Running From

How do I get the directory that a program is running from?

Here's code to get the full path to the executing app:

Windows:

char pBuf[256];
size_t len = sizeof(pBuf);
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;

Linux:

int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
return bytes;

How to get the directory of the currently running file?

This should do it:

import (
"fmt"
"log"
"os"
"path/filepath"
)

func main() {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
fmt.Println(dir)
}

Finding the path of the program that will execute from the command line in Windows

Use the where command. The first result in the list is the one that will execute.


C:\> where notepad
C:\Windows\System32\notepad.exe
C:\Windows\notepad.exe

According to this blog post, where.exe is included with Windows Server 2003 and later, so this should just work with Vista, Win 7, et al.

On Linux, the equivalent is the which command, e.g. which ssh.

Executable directory where application is running from?

Dim strPath As String = System.IO.Path.GetDirectoryName( _
System.Reflection.Assembly.GetExecutingAssembly().CodeBase)

Taken from HOW TO: Determine the Executing Application's Path (MSDN)

How to get execution directory of console application

Use Environment.CurrentDirectory.

Gets or sets the fully qualified path of the current working directory.

(MSDN Environment.CurrentDirectory Property)

string logsDirectory = Path.Combine(Environment.CurrentDirectory, "logs");

If your application is running in c:\Foo\Bar logsDirectory will point to c:\Foo\Bar\logs.

How to get the execution directory path in java [duplicate]

As Jarrod Roberson states in his answer here:

One way would be to use the system property
System.getProperty("user.dir"); this will give you "The current
working directory when the properties were initialized". This is
probably what you want. to find out where the java command was
issued, in your case in the directory with the files to process, even
though the actual .jar file might reside somewhere else on the
machine. Having the directory of the actual .jar file isn't that
useful in most cases.

The following will print out the current directory from where the
command was invoked regardless where the .class or .jar file the
.class file is in.

public class Test
{
public static void main(final String[] args)
{
final String dir = System.getProperty("user.dir");
System.out.println("current dir = " + dir);
}
}

if you are in /User/me/ and your .jar file containing the above code
is in /opt/some/nested/dir/ the command java -jar
/opt/some/nested/dir/test.jar Test
will output current dir =
/User/me
.

You should also as a bonus look at using a good object oriented
command line argument parser. I highly recommend JSAP, the Java
Simple Argument Parser. This would let you use
System.getProperty("user.dir") and alternatively pass in something
else to over-ride the behavior. A much more maintainable solution.
This would make passing in the directory to process very easy to do,
and be able to fall back on user.dir if nothing was passed in.

Example : GetExecutionPath

import java.util.*;
import java.lang.*;

public class GetExecutionPath
{
public static void main(String args[]) {
try{
String executionPath = System.getProperty("user.dir");
System.out.print("Executing at =>"+executionPath.replace("\\", "/"));
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
}
}

output for the above will be like

C:\javaexamples>javac GetExecutionPath.jav

C:\javaexamples>java GetExecutionPath
Executing at =>C:/javaexamples

How to get Current Directory?

I would recommend reading a book on C++ before you go any further, as it would be helpful to get a firmer footing. Accelerated C++ by Koenig and Moo is excellent.

To get the executable path use GetModuleFileName:

TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );

Here's a C++ function that gets the directory without the file name:

#include <windows.h>
#include <string>
#include <iostream>

std::wstring ExePath() {
TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );
std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\\/");
return std::wstring(buffer).substr(0, pos);
}

int main() {
std::cout << "my directory is " << ExePath() << "\n";
}

How do I get the executing program's directory in C using a plataform independent method?

Under Unix like operating systems that have the /proc directory you can readlink /proc/self/exe to get the actual executable files full path even when argv[0] does not have this.

This may not work, however, if the executable was started with fexecv (not available on many systems) and if that is implemented as a system call on your system. fexecv is just like execve except that it is passed an open file descriptor rather than a filename to run. Under Linux it is implemented by calling execve on the string generated by `"/proc/self/%i", fd", so the file would have to live in the file system at the time the program was started.

I think that GNU/Hurd supports fexecve natively.

It is possible for an executable file to be renamed or unlinked from the filesystem after it has been executed which makes it become an unnamed file which will go away as soon as it ceases to be open (in this context running a file usually requires it to be open by the kernel).

Get current folder path

You should not use Directory.GetCurrentDirectory() in your case, as the current directory may differ from the execution folder, especially when you execute the program through a shortcut.

It's better to use Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); for your purpose. This returns the pathname where the currently executing assembly resides.

While my suggested approach allows you to differentiate between the executing assembly, the entry assembly or any other loaded assembly, as Soner Gönül said in his answer,

System.IO.Path.GetDirectoryName(Application.ExecutablePath);

may also be sufficient. This would be equal to

System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);


Related Topics



Leave a reply



Submit