C# cmd 生成 exe文件
生成单独的exe文件
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe Program.cs
生成 exe 文件的步骤如下:
1. 使用文本编辑器(如 Notepad++ 或 Visual Studio Code)编写 C# 源代码,并将其保存为 .cs 文件(例如,`Program.cs`)。
2. 打开一个命令提示符(在 Windows 中按下 Windows + R 键,并输入 cmd)。
3. 导航到 .cs 文件所在的文件夹。例如,使用 `cd C:\\MyProjects\\MyCSharpApp`。
4. 运行以下命令开始编译过程:`csc Program.cs` 。如果你的程序中还有其他 .cs 文件,也需要将它们传递给 csc 命令。
5. 编译成功后,您将在当前文件夹中看到一个名为 `Program.exe` 的新文件。运行该文件,您的程序将在命令行环境中执行。
--------- 摘自《MSDN》
若要生成文件 MathLibrary.DLL,请使用以下命令行编译文件 Add.cs 和文件 Mult.cs:
csc /target:library /out:MathLibrary.DLL Add.cs Mult.cs
/target:library 编译器选项通知编译器输出 DLL 文件而不是 EXE 文件。后跟文件名的 /out 编译器选项用于指定 DLL 文件名。否则,编译器使用第一个文件 (Add.cs) 作为 DLL 文件名。
若要生成可执行文件 TestCode.exe,请使用以下命令行:
csc /out:TestCode.exe /reference:MathLibrary.DLL TestCode.cs
/out 编译器选项通知编译器输出 EXE 文件并且指定输出文件名 (TestCode.exe)。此编译器选项是可选的。/引用编译器选项指定该程序使用的 DLL 文件。
结论:使用 /reference 引用Dll文件。
示例参考:
// 要进入的目录
public string workingDirectory { set; get; } = string.Empty;
private void Button_Click(object sender, RoutedEventArgs e)
{
MainRun();
}
private void MainRun()
{
// 创建一个ProcessStartInfo对象
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "cmd.exe", // 指定cmd.exe作为程序执行
RedirectStandardInput = true, // 允许写入输入流
UseShellExecute = false, // 不使用系统外壳程序启动
CreateNoWindow = true, // 不创建新窗口
WorkingDirectory = workingDirectory // 设置工作目录
};
// 设置其他需要引用的类库路径
string[] references = new string[]
{
"RestSharp.dll",
"Newtonsoft.Json.dll"
};
string referencesBuilder = string.Join(" ", references.Select(r => $"/r:{r}"));
// 启动进程
using (Process process = Process.Start(startInfo))
{
// 写入命令
using (System.IO.StreamWriter sw = process.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
StringBuilder stringBuilder = new StringBuilder();
string[] files = Directory.GetFiles(workingDirectory);
foreach (var file in files)
{
if (System.IO.Path.GetExtension(file).Equals(".cs"))
{
stringBuilder.AppendFormat("{0} ", file);
}
}
// 例如:执行dir命令
sw.WriteLine($@"csc /out:ClassLibrary1.dll {referencesBuilder} /t:library {stringBuilder}");
// 更多的命令...
// sw.WriteLine("your other commands here");
// 结束输入
sw.Close();
}
}
// 等待程序执行完成
process.WaitForExit();
}
}
private void btnPath_Click(object sender, RoutedEventArgs e)
{
using var dialog = new FolderBrowserDialog
{
Description = "选择目录",
UseDescriptionForTitle = true,
ShowNewFolderButton = true
};
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
workingDirectory = dialog.SelectedPath.Trim();
Dispatcher.Invoke(new Action(() => {
txtPath.Text = workingDirectory;
}));
}

浙公网安备 33010602011771号