Search code examples
c#linuxmono

How to execute Linux command line in C# Mono


I want to execute this command : iconv -f unicode -t utf8 input.txt > output.txt

But I got this error : /usr/bin/iconv: cannot open input file `>': No such file or directory

            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = "/usr/bin/iconv";
            psi.UseShellExecute = false;
            psi.Arguments = "-f unicode -t utf8 /tmp/test.txt > Desktop/output.txt";
            Process p = Process.Start(psi);
            p.WaitForExit();
            p.Close();

Solution

  • You can only use the <, > and | operators inside a shell. The shell (such as bash) is what actually parses these and performs the redirection. Try this code:

    ...
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "/usr/bin/iconv";
    psi.UseShellExecute = false;
    psi.Arguments = "-f unicode -t utf8 /tmp/test.txt";
    psi.RedirectStandardOutput = true;
    Process p = Process.Start(psi);
    Console.WriteLine(p.StandardOutput.ReadToEnd());
    p.WaitForExit();
    p.Close();
    ...
    

    I apologize if this code doesn't work properly, I personally rarely program in C#.

    You may also be able to just set psi.UseShellExecute = true. According to MSDN, this will start the program with the system shell (cmd.exe). This may work for you, although I have not tested.

    Best of luck!