shawnblais
shawnblais

Reputation: 1248

dart:io Process - How to run 'CMD start' on Windows?

On Linux we are able to open url's using a simple io.Process call:

io.Process.run("xdg-open", [ url, ])

But trying to do the equivalent thing on windows

io.Process.run("start", [url]);

It fails with: The system cannot find the file specified.

I'm guessing we need the path of cmd.exe, which is located at %ComSpec%. Tried doing a 'echo %ComSpec%, but getting the same error. Also tried hard-coding the path, but no success.

Here is our complete function:

ProcessResult result;
  try {
    if(Platform.isLinux){
      result = await io.Process.run("xdg-open", [ url, ]);
    }
    else if(Platform.isWindows){
      result = await io.Process.run("start", [url]);
    }
  } on ProcessException catch (e){
    Log.e(e?.message);
  };
  return result?.exitCode == 0;

[Edit] Updated title to be more accurate

Upvotes: 5

Views: 8386

Answers (2)

Олег
Олег

Reputation: 11

Work example for Windows -

Future<io.ProcessResult> processRun() {
 var result = io.Process.run(
  'C:\\Program Files (x86)\\1cv8\\common\\1cestart.exe', [],
  runInShell: true);

   result.then((value) {
     print(value.exitCode);
   });

return result; }

Upvotes: 1

smorgan
smorgan

Reputation: 21569

The title of your question doesn't match your code; that isn't trying to run cmd.exe, it's trying to run an executable called start. The reason it doesn't work is that start isn't an executable, it's a command built into cmd.exe's interpreter. (Try running where start at a command prompt; compare with where cmd.)

If you want to run a cmd.exe command like start, you need to pass runInShell: true to Process.run. However, keep in mind that if you do you may need to be careful about special characters in your arguments.

(The answer to the question in your title is: Process.run('cmd', [...]);. But since what you want to do is run a command in the shell it's easier to use runInShell: true than to invoke cmd with /c and your command as a string.)

Upvotes: 11

Related Questions