c# - 在 C# 中运行 cmd
问题描述
有什么区别:
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:
目录,那么如何cmd.exe
在Visual Studio项目文件夹中运行呢?
谢谢
解决方案
像这样的东西:
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)) {
...
}
推荐阅读
- haskell - Coyoneda没有更高级别的类型,但它实际上是什么类型?
- python - 在 pandas、python 中找到另一种使用 groupby 的方法
- python - 从 Python 中的超类实例扩展子类实例
- javascript - 如何使用 React suspense 更新 redux 存储
- amazon-web-services - 如何从 AWS 聊天机器人运行 codepipeline
- javascript - Gatsbyjs 页面相似标志灰色轮播
- python - Path.rglob() raising FileNotFoundError on Linux system
- android - React Native Depth in a View
- gradle - Gradle:启动任务时无法转义特殊字符
- python - 在 Colab 中使用 CUDA