How do I get the current executing directory on linux with .Net Core?
I need to load in an XML schema file to validate some information on a .Net Core 2.1 api that is on a linux server. Unfortunately, I do not have access to this server (we use jenkins to deploy so I have 0 contact with it), so I can only test on my computer which is Windows 10.
I have tried the following:
All of these return the current execution location on Windows (i.e. C:/SomePath/SomeProject/Name/api.dll ) which I can use with Path.Combine to produce the path to the schema file.
However, on linux, these all return /home/app/ which is not where the dll should be according to the Jenkins logs. This is leading to failures loading the schema file. The project is actually located under /services/projectname/ .
Expected: On Windows and Linux this loads the schema file using the .dll execution path as the base.
Actual: On Linux I get home/app instead of the correct path.
Edit: I cannot hardcode the path. The path changes on every deployment as the project name is versioned. This means the second I deploy it, any hardcoded value will be incorrect. I absolutely require a relative path. Beyond that technical requirement, hard coding is a major taboo. I will never get it past a code review.
How to get Current Directory?
I’ve been doing this in C# and Delphi ,but C++ is evil.The purpose is to create a file in the current directory(where the executable is running).
I get exception at GetCurrentDirectory().
Please tell me why I get an exception and how do I make it easier in C++?
18 Answers 18
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:
Here’s a C++ function that gets the directory without the file name:
GetCurrentDirectory does not allocate space for the result, it’s up to you to do that.
Also, take a look at Boost.Filesystem library if you want to do this the C++ way.
The question is not clear whether the current working directory is wanted or the path of the directory containing the executable.
Most answers seem to answer the latter.
But for the former, and for the second part of the question of creating the file, the C++17 standard now incorporates the filesystem library which simplifies this a lot:
How to get current working directory path c#?
I have a cursor file in project. I have given the absolute path in code i.e
the problem is this is hard-coded path And i Want relative path so that if i move my solution to another system the code should not effect.
please suggest how to set relative path
7 Answers 7
You can use static Directory class — however current directory is distinct from the original directory, which is the one from which the process was started.
So you can use the following to get the directory path of the application executable:
use Application.StartupPath returns path for the executable file that started the application.
You can also get by
System.IO.Directory.GetCurrentDirectory();
but it shows bin and debug folder also, if you don’t want these folder so you can use that code :
GetFileName: Mouse.aspx
GetFileNameWithoutExtension: Mouse
GetDirectoryName: E:\abccom\Cat
Happy Coding 🙂
You can get the current working directory by using System.IO.Directory.GetCurrentDirectory() . it will return your current executable path.
Application.StartupPath should give you application path from where your application is running. I would create a directory structure under application folder. e.g If «C:\Program Files\MyApp» is my application folder, then I would create a folder named cursors under it (C:\Program Files\MyApp\Cursors») and put all cursors within this folder.
System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) at startup will give you the full path.
After that, if you * really want to find something during development (as your comments in other answers point) *, first find the path using FileInfo(thestringwithfilenamepath).Directory.Name .
Super late to this party, but this works for me when I’m in unit tests.
If you need the root of the project, and not the bin directory then this:
getting current directory in linux for argument
I’m learning Linux scripting and trying to set up a function that finds all files in the current directory. I know I could use ls but I’m wondering if there is a way to get the current directory as a command and pass it to an argument.
This just prints out pwd:, which obviously isn’t it.
4 Answers 4
PWD variable does exactly what you want. So just replace pwd with $PWD and you are done
To execute a command and use its output in your script as a parameter, just use back quotes. In your case, it would be:
A more modern variant is to use the $( . ) notation (which can be nested when needed, and is expanded to the output of the command in between $( and matching ) ) instead of the backquotes, eg
(but $PWD would work too since shells maintain their PWD variable, see Posix shell).
Read also the advanced bash scripting guide (which can be criticized but is a good start).
$PDW
the present working directory is stored in the variable named $PWD
Display the full working directory name
Display the working directory name
Can also use the symbol *
is a short cut to a list of files in the present working directory .
Loop through them :
Function looping through
Store the present directory name in a variable and use it in a function
Changing the current directory in Linux using C++
I have the following code:
The purpose of this code is pretty self explanatory: to set a user specified directory as the current directory. My plan is to carry out operations on the files contained therein. However, when I attempt to compile this code, I receive the following error
with reference being made to the line reading int chdir(sDirectory) . I’ve just started programming and am only now starting to have to find out about platform specific functions, which this one is, so any help on this matter would be most appreciated.
3 Answers 3
int chdir(sDirectory); isn’t the correct syntax to call the chdir function. It is a declaration of an int called chdir with an invalid string initializer (`sDirectory).
To call the function you just have to do:
Note that chdir takes a const char* , not a std::string so you have to use .c_str() .
If you want to preserve the return value you can declare an integer and use a chdir call to initialize it but you have to give the int a name:
Finally, note that in most operating system the current or working directory can only be set for the process itself and any children it creates. It (almost) never affects the process that spawned the process changing its current directory.
If you expect to find the working directory of your shell to be changed once your program terminates you are likely to be disappointed.
How do I get the directory that a program is running from?
Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don’t suggest libraries unless they’re standard ones like clib or STL.)
(If there’s no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)
.exe file) is located, and the ‘current working directory’ is the directory, that is autocompleted if the program uses relative paths? – colemik Apr 24 ’13 at 9:53
23 Answers 23
Here’s code to get the full path to the executing app:
If you fetch the current directory when your program first starts, then you effectively have the directory your program was started from. Store the value in a variable and refer to it later in your program. This is distinct from the directory that holds the current executable program file. It isn’t necessarily the same directory; if someone runs the program from a command prompt, then the program is being run from the command prompt’s current working directory even though the program file lives elsewhere.
getcwd is a POSIX function and supported out of the box by all POSIX compliant platforms. You would not have to do anything special (apart from incliding the right headers unistd.h on Unix and direct.h on windows).
Since you are creating a C program it will link with the default c run time library which is linked to by ALL processes in the system (specially crafted exceptions avoided) and it will include this function by default. The CRT is never considered an external library because that provides the basic standard compliant interface to the OS.
On windows getcwd function has been deprecated in favour of _getcwd. I think you could use it in this fashion.
On windows:
On Linux:
On HP-UX:
If you want a standard way without libraries: No. The whole concept of a directory is not included in the standard.
If you agree that some (portable) dependency on a near-standard lib is okay: Use Boost’s filesystem library and ask for the initial_path().
IMHO that’s as close as you can get, with good karma (Boost is a well-established high quality set of libraries)
I know it is very late at the day to throw an answer at this one but I found that none of the answers were as useful to me as my own solution. A very simple way to get the path from your CWD to your bin folder is like this:
You can now just use this as a base for your relative path. So for example I have this directory structure:
and I want to compile my source code to bin and write a log to test I can just add this line to my code.
I have tried this approach on Linux using full path, alias etc. and it works just fine.
If you are on windows you should use a ‘\’ as the file separator not ‘/’. You will have to escape this too for example:
I think this should work but haven’t tested, so comment would be appreciated if it works or a fix if not.
Filesystem TS is now a standard ( and supported by gcc 5.3+ and clang 3.9+ ), so you can use current_path() function from it:
In gcc (5.3+) to include Filesystem you need to use:
and link your code with -lstdc++fs flag.
If you want to use Filesystem with Microsoft Visual Studio, then read this.
No, there’s no standard way. I believe that the C/C++ standards don’t even consider the existence of directories (or other file system organizations).
On Windows the GetModuleFileName() will return the full path to the executable file of the current process when the hModule parameter is set to NULL. I can’t help with Linux.
Also you should clarify whether you want the current directory or the directory that the program image/executable resides. As it stands your question is a little ambiguous on this point.
On Windows the simplest way is to use the _get_pgmptr function in stdlib.h to get a pointer to a string which represents the absolute path to the executable, including the executables name.
Maybe concatenate the current working directory with argv[0]? I’m not sure if that would work in Windows but it works in linux.
When run, it outputs:
/Desktop$ ./test
/home/jeremy/Desktop/./test
For Win32 GetCurrentDirectory should do the trick.
You can not use argv[0] for that purpose, usually it does contain full path to the executable, but not nessesarily — process could be created with arbitrary value in the field.
Also mind you, the current directory and the directory with the executable are two different things, so getcwd() won’t help you either.
On Windows use GetModuleFileName(), on Linux read /dev/proc/procID/.. files.
Just to belatedly pile on here.
there is no standard solution, because the languages are agnostic of underlying file systems, so as others have said, the concept of a directory based file system is outside the scope of the c / c++ languages.
on top of that, you want not the current working directory, but the directory the program is running in, which must take into account how the program got to where it is — ie was it spawned as a new process via a fork, etc. To get the directory a program is running in, as the solutions have demonstrated, requires that you get that information from the process control structures of the operating system in question, which is the only authority on this question. Thus, by definition, its an OS specific solution.
For Windows system at console you can use system( dir ) command. And console gives you information about directory and etc. Read about the dir command at cmd . But for Unix-like systems, I don’t know. If this command is run, read bash command. ls does not display directory.
On POSIX platforms, you can use getcwd().
On Windows, you may use _getcwd(), as use of getcwd() has been deprecated.
For standard libraries, if Boost were standard enough for you, I would have suggested Boost::filesystem, but they seem to have removed path normalization from the proposal. You may have to wait until TR2 becomes readily available for a fully standard solution.
For relative paths, here’s what I did. I am aware of the age of this question, I simply want to contribute a simpler answer that works in the majority of cases:
Say you have a path like this:
For some reason, Linux-built executables made in eclipse work fine with this. However, windows gets very confused if given a path like this to work with!
As stated above there are several ways to get the current path to the executable, but the easiest way I find works a charm in the majority of cases is appending this to the FRONT of your path:
Just adding «./» should get you sorted! 🙂 Then you can start loading from whatever directory you wish, so long as it is with the executable itself.
EDIT: This won’t work if you try to launch the executable from code::blocks if that’s the development environment being used, as for some reason, code::blocks doesn’t load stuff right. 😀
EDIT2: Some new things I have found is that if you specify a static path like this one in your code (Assuming Example.data is something you need to load):
If you then launch your app from the actual directory (or in Windows, you make a shortcut, and set the working dir to your app dir) then it will work like that. Keep this in mind when debugging issues related to missing resource/file paths. (Especially in IDEs that set the wrong working dir when launching a build exe from the IDE)