How to add custom command line in .NET 6 api project

46 Views Asked by At

Good evening everyone!

I have a .NET 6 api project in which we have a data import from csvs that works in background with a Quartz job. There is a service class (IImportService) in which every csv is read from a local folder, then converted in DataTable, for every row of that DataTable a new object of that entity is created (e.g. product.csv, for every row is created an object of type Product) and then added to db.

What I need to implement is a way to start that Import method with command line, but I don't understand how to do it. I've read about adding a console app project to the same solution and add main project's namespaces so that I have everything I need to create a CLI command that start Import method. Or I've read about the fact that a .NET application already is a CLI application so that I can run the application and do something I haven't quite understand.

The thing is that these solutions seem too complicated to me considering the simplicity of the request, so I was wondering if I was actually missing out on a much simpler solution.

Hoping you can help me understand more about it!

1

There are 1 best solutions below

3
KnuturO On

I use System.Diagnostics in an API project to do this:

    public static void RunCommand(string command)
    {
        try
        {
            Process process = new();
            ProcessStartInfo startInfo = new();
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/C " + command;
            process.StartInfo = startInfo;
            process.Start();
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.Message);
        }
    }

I call it like this:

RunCommand("sc create LyklakippanService binpath=\"C:\\Program Files\\Prod\\Lyklakippan\\LyklakippanService.exe\" start=auto");