Search code examples
c#windowscmd.net-5rider

Run console application from the command prompt


I created a console application using Jetbrains rider. I then published the console application to a folder. I added the folder to my System path. I can run echo %PATH% and see that the folder is in the path however I can only run the console application if I am inside the folder. It doesn't event work if I put the full path to the executable.

C:\Program Files<Company Name><Program Name><files>

I also checked the files permissions against another file and that seems to be the same. I disabled a virus protection and that didn't fix the issue either.

Any thoughts on why this will not run? I am running windows 10.

Solution

Set the base path while creating the applications configuration.

builder
    .SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location)) // set the base path
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables();

Solution

  • Your application is not good coded. It most likely references other files stored in the directory of the executable without using any path which means with referencing the files using a path relative to current directory.

    See the Microsoft documentation about Naming Files, Paths, and Namespaces.

    The current directory for your application can be by chance the directory containing the application executable, but there are thousands of other directories which can be the current directory on starting the application.

    Every programming/scripting language has a method to determine/get the full qualified path of itself, i.e. in which directory the currently executed executable or interpreted script file is stored which is called the application directory or the program files directory or the script directory.

    This path must be concatenated with the file names of other files in same directory as the executable/script or a subdirectory of the application/script directory. Then it does no longer matter for the executable/script which directory is the current directory as it references itself all its files/folders with full qualified name.

    The solution could be using in code:

    builder.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location))
    

    See also: How can I get the application's path in a .NET console application?