c# - 在 C# 中运行 cmd

标签 c# cmd directory project

有什么区别:

var startInfo = new ProcessStartInfo();
string path = Directory.GetCurrentDirectory() + @"\foldername";
startInfo.WorkingDirectory = path;
startInfo.FileName = path + @"\do_run.cmd";
startInfo.Arguments = "/c arg1 arg2";
Process.Start(startInfo);

var startInfo = new ProcessStartInfo();
string path = Directory.GetCurrentDirectory() + @"\foldername";
startInfo.FileName = @"C:\windows\system32\cmd.exe";
startInfo.Arguments = @"/c cd " + path + " && do_run arg1 arg2";
Process.Start(startInfo);

出于某种原因,第二个代码块可以正常工作,但第一个代码块不能。

其次,我无法在发布应用程序时使用我的C:目录,那么如何在Visual Studio项目文件夹中运行cmd.exe

谢谢

最佳答案

像这样的东西:

using System.IO;
using System.Reflection;

... 

var startInfo = new ProcessStartInfo();

// We want a standard path (special folder) which is C:\windows\system32 in your case
// Path.Combine - let .Net make paths for you 
startInfo.FileName = Path.Combine(
  Environment.GetFolderPath(Environment.SpecialFolder.System), 
 "cmd.exe");

string path = Path.Combine(
  // If you want exe path; change into 
  //   Environment.CurrentDirectory if you want current directory
  // if you want current directory
  Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), 
 @"foldername");

// ""{path}"" - be careful since path can contain space(s)
startInfo.Arguments = $@"/c cd ""{path}"" && do_run arg1 arg2";

// using : do not forget to Dispose (i.e. free unmanaged resources - HProcess, HThread)
using (Process.Start(startInfo)) {
  ... 
}

关于c# - 在 C# 中运行 cmd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53701968/

相关文章:

c# - 帮助我的简单 winforms 游戏

batch-file - Windows 批处理文件 : Pipe destroys my return code

cmd - 刷新 Azure Pipeline 构建中的环境变量

perl - 如何使用 Perl 列出具有特定名称模式的目录下的文件?

c# - 使用 mvvm light 实现文件计数器

c# - 将 XML 属性读入列表

c# - 快速更新值时如何防止WinForms中的闪烁?

c# - 创建 msbuild 脚本以使用指定的 app.config 进行构建、发布以及从不同位置进行更新

linux - 如何在 Linux 上查找包含特定文本(字符串)的所有文件?

python - 文件夹名称带有\n