Search code examples
c#.net-core

Adding .NET Core App to Command Line Path


In the past I made some simple C# command line apps and put them in a directory that I added to my PATH environment variable. For example, I made a tool to open a random image from the current directory. The executable for this would be at:

C:\Users\myuser\Scripts\RandomImage.exe

Then I would navigate to a directory I had a bunch of images in and I could just run this from the command line:

L:\Resources\SourceFiles> RandomImage

And it would open a random image. How can I do this with .NET Core? I've modified the project.json as instructed from the docs.

"version": "1.0.0-*",
"buildOptions": {
  "emitEntryPoint": true
},

"dependencies": {
  "Microsoft.NETCore.App": {
    "version": "1.0.1"
  }
},

"frameworks": {
    "netcoreapp1.0": {
        "imports": "dnxcore50"
    }
},

"runtimes": {
    "win10-x64": {}
}

Then I run the publish command specifying the runtime.

dotnet publish -c release -r win10-x64

With this, I can navigate to the publish directory and run my executable on any Windows 10 (64 bit) machine. But I need the full path to that file in order to run it from any other directory. Is there a way to do this with .NET Core without requiring the full path? I have several of these little apps and I use them from different machines, so I don't want to add an environment variable for each one on each machine.


Solution

  • A simple way to solve this problem (assuming you have dotnet on your PATH) would be to create a simple CMD script to launch the program.

    Example

    Directory the CMD is in (expected to be on Path): C:\Users\myuser\Scripts
    Directory you deploy to: C:\Users\myuser\Scripts\RandomImage
    Name of the CMD file: RandomImage.cmd

    Content of the CMD file:

    @dotnet "%~dp0\RandomImage\RandomImage.dll" %*
    

    %~dp0 is the Path of the script itself
    %* Passes all arguments to the DLL

    You could then use it like this:

    L:\Resources\SourceFiles> RandomImage arg1 arg2