执行CAT命令覆盖文件
我正在尝试从 C# 代码执行 cat 命令,但遇到了问题。
所以,这只是一个非常简单的测试,但我最终得到了错误:
错误:cat:'>':没有这样的文件或目录
现在...源文件和目标文件实际上都存在如果目标文件不存在,则结果相同。
如果我在 Raspberry Pi 上打开控制台,它就会正常执行。非常感谢任何帮助。
我的代码:
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}";
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 = quot;-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(quot;Args: {info.Arguments}");
sb.AppendLine(quot;Output: {p!.StandardOutput.ReadToEnd()}");
sb.AppendLine(quot;Error: {p!.StandardError.ReadToEnd()}");
p!.WaitForExit();
return quot;Overwrite system file {path}: {p.ExitCode}{Environment.NewLine}{sb}";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为您正在向
cat
程序传递>
参数。>
仅在bash
或sh
进程中有意义,它告诉解释器应转储stdout
输出进入文件
。它不是cat
的有效参数。要解决此问题,请在 shell 中调用
cat
进程:在 C# 中,
您也可以使用 C# 的
File
实用程序读取第一个文件并将其内容写入第二个文件。由于 I/O 操作较少,可能会更快。我已经修复了我的样本。使用双引号代替单引号:
This is because you're passing the
cat
program the>
argument.>
only makes sense inbash
orsh
process where it tells to the interpreter thatstdout
outputs should be dumped intofile
. It's not a valid argument forcat
.To get around this, invoke your
cat
process within your shell:In C#
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: