C# -----通过操作系统命令编译.cs 生成dll
public class CodeDll
{
public string DllName = "MyName.dll";
public string CsFilePath = "Path";
public string Compile()
{
string result = string.Empty;
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
Process process = new Process();
//设置启动进程的属性
process.StartInfo.FileName = "cmd.exe";
//不使用操作系统的shell启动进程
process.StartInfo.UseShellExecute = false;
//设置应用程序的输入从Process.StandardInput 流中读取值
process.StartInfo.RedirectStandardInput = true;
//设置应用程序的文本输出写入Process.StandardOutput流中的值
process.StartInfo.RedirectStandardOutput = true;
//设置应用错误输出写入Process.StandardError流中的值
process.StartInfo.RedirectStandardError = true;
//设置在新窗口中启动该进程的值
process.StartInfo.CreateNoWindow = true;
process.Start();
string value = string.Format("C:", Array.Empty<object>());
//将字符串"C:"写入流
process.StandardInput.WriteLine(value);
value = string.Format("cd C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319", Array.Empty<object>());
//将字符串 以上地址写入流
process.StandardInput.WriteLine(value);
//将.CS 生成dll 的命令行字符串
StringBuilder stringBuilder = new StringBuilder();
string text = baseDirectory + this.DllName;
string text2 = baseDirectory + this.CsFilePath;
string text3 = baseDirectory + "MM.xml";
//bool flag = this.CsFilesList.Count == 0;
bool flag=true;
if (flag)
{
stringBuilder.Append(string.Concat(new string[]
{
"csc /t:library /out:",
text,
" ",
text2,
"\\*cs /doc:",
text3
}));
}
value = stringBuilder.ToString();
process.StandardInput.WriteLine(value);
Thread.Sleep(4000);
process.StandardInput.WriteLine("exit");
result = process.StandardOutput.ReadToEnd();
string text4 = process.StandardError.ReadToEnd();
process.StandardError.Close();
bool flag2 = !string.IsNullOrEmpty(text4);
if (flag2)
{
MessageBox.Show(text4);
}
return result;
}
}
将所有想要生成dll 的.cs文件放置在Path 目录下, 调用以上方法,就可以生成MyName.dll 文件咯!
这是一个Demo,更多复杂的内容和实现方法,比如生成.exe.生成项目文件等,需要再研究哦!