Skip to content
Advertisement

Execute cat command to overwrite file

I am trying to execute the cat command from my C# code, but I am running into problems.

So, this is just a very simple test, but I end up with the error:

Error: cat: ‘>’: No such file or directory

Now… both source and target files actually exist.. and same result if target file does not exist.

If I open a console on my Raspberry Pi, it executes just fine. Any help is much appreciated.

My code:

        var srcFile = "/home/pi/tm-satellite/Helpers/wpa_supplicant.conf";
        var outFile = "/home/pi/tm-satellite/network-test.txt";

        StringBuilder sb = new StringBuilder();

        var info = new ProcessStartInfo();
        info.FileName = "/bin/bash";
        info.Arguments = $"-c 'cat {srcFile} > {outFile}'";

        info.UseShellExecute = false;
        info.CreateNoWindow = true;

        info.RedirectStandardOutput = true;
        info.RedirectStandardError = true;

        var p = Process.Start(info);

        //* Read the output (or the error)
        sb.AppendLine($"Args: {info.Arguments}");
        sb.AppendLine($"Output: {p!.StandardOutput.ReadToEnd()}");
        sb.AppendLine($"Error: {p!.StandardError.ReadToEnd()}");
        
        p!.WaitForExit();

        return $"Overwrite system file {path}: {p.ExitCode}{Environment.NewLine}{sb}";

Advertisement

Answer

This is because you’re passing the cat program the > argument.

> only makes sense in bash or sh process where it tells to the interpreter that stdout outputs should be dumped into file. It’s not a valid argument for cat.

To get around this, invoke your cat process within your shell:

sh -c 'cat file1 > file2'

In C#

var srcFile = "/home/pi/tm-satellite/Helpers/wpa_supplicant.conf"
var outFile = "/home/pi/tm-satellite/network-test.txt"
var info = new ProcessStartInfo();
info.FileName = "sh";
info.Arguments = $"-c 'cat {srcFile} > {outFile}'";

Alternatively you can use C#’s File utilities to read the first file and write its contents into the second as it might be faster due to less I/O operations.


I’ve fixed my sample. Use double quotes instead of single quotes:

var srcFile = "~/bad";
var outFile = "~/good";
                
var pInfo = new ProcessStartInfo()
{
  FileName = "sh",
  Arguments = $"-c "cat {srcFile} > {outFile}""
};

var process = Process.Start(pInfo);
process.WaitForExit();
Advertisement