---
title: "C#调用Shell命令"
author: "Perrin Yong"
author_profile: https://www.pystone.net/profile/
published_by: "Perrin Yong"
canonical: https://www.pystone.net/notes/csharp-shell-command-invocation/
type: note
content_role: unspecified
visibility: public
id_stability: rename-stable
source_path: "10-计算机、信息技术与工程/02-编程语言与运行时/.NET与CSharp/C#调用Shell命令.md"
content_hash: e36b9360b450019fee6480d8fac6d19f2d03ae61b2f0e28e8d13743a81b29e42
knowledge_version: 224c990773de.5fa8af6e39fa
site_commit: 224c990773de166d23a886306577dd90379529ce
notes_commit: 5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a
---
# C#调用Shell命令

> 创建时间：2020/10/23 12:10

使用C#在Windows系统上调用命令行，在MacOS上调用bash，笔者在实现时遇到了很多坑，记录下来。
以下代码亲测直接可用。在某些版本中，使用某个方法可能会出问题，选一个使用即可。

## 类Unix系统上调用bash

通过StartInfo.Arguments参数，只执行一行命令。

```xml
public class UsingEnum&lt;T&gt; where T : System.Enum { }
public class UsingDelegate&lt;T&gt; where T : System.Delegate { }
public class Multicaster&lt;T&gt; where T : System.MulticastDelegate { }

```

通过重定向标准输入输出流，一行一行执行命令

```xml
public class UsingEnum&lt;T&gt; where T : System.Enum { }
public class UsingDelegate&lt;T&gt; where T : System.Delegate { }
public class Multicaster&lt;T&gt; where T : System.MulticastDelegate { }

```

标准输入输出的方式也可以写一行，在行末尾加exit 命令，退出。
如果不执行exit命令，调用StandardOutput.ReadToEnd，会由于无法读到终止符而阻塞进程。

```xml
public class UsingEnum&lt;T&gt; where T : System.Enum { }
public class UsingDelegate&lt;T&gt; where T : System.Delegate { }
public class Multicaster&lt;T&gt; where T : System.MulticastDelegate { }

```

## windows系统调用CMD

理论上与UNIX-like系统调用shell命令方式相同
以下为一行命令执行完的方法。由于在CMD中ReadToEnd会读出多余信息，这里提供一个CMDOutputFilter函数过滤多余的信息。

```xml
public class UsingEnum&lt;T&gt; where T : System.Enum { }
public class UsingDelegate&lt;T&gt; where T : System.Delegate { }
public class Multicaster&lt;T&gt; where T : System.MulticastDelegate { }

```

以luacheck工具为例，测试以上函数

```csharp
class MyClass&lt;T, U&gt;
    where T : class
    where U : struct
{ }

```
