c# - How to Start and Fire a Command
问题描述
It is supposed to be easy, but I can't get it work.
When I run the following command inside cmd, it works perfectly fine. When I run the command inside the c#
code, it won't do anything (no exception has been thrown either).
Here is the command I'm using (which works perfectly fine when using directly on cmd.exe
):
cd %ProgramFiles%\PostgreSQL\12\bin && SET PGPASSWORD=mypassword&& pg_restore.exe -U username -d dbname C:\file\to\dump\my.dump
Here is what I'm trying to do in c#
(not working):
var arg = @"cd %ProgramFiles%\PostgreSQL\12\bin && SET PGPASSWORD=mypassword&& pg_restore.exe -U username -d dbname C:\file\to\dump\my.dump";
Process.Start("cmd.exe", arg);
Am I missing something? I found a lot of posts concerning c#
starting a process, but nothing solved my problem. I also tried to start the process with StartInfo
and added the Properties like Arguments
, FileName
, etc., but it did not work either.
Be aware, the question process.start() arguments is not the same - in my case, I neet to set the system variable (SET PGPASSWORD)
, since pg_restore
has no password argument.
解决方案
cmd
只是控制台,不需要启动另一个进程。
您要运行的应用程序pg_restore.exe
位于该%ProgramFiles%\PostgreSQL\12\bin
文件夹中。您可以通过ProcessStartInfo.EnvironmentVariables字典传递环境变量。我不确定 ProcessStartInfo 构造函数是否扩展了环境变量。您可以使用Environment.ExpandEnvironmentVariables确保路径正确:
var binFolder=@"%ProgramFiles%\PostgreSQL\12\bin\";
var fullPath=Path.Combine(binFolder,"pg_restore.exe");
var arguments=@"-U username -d dbname C:\file\to\dump\my.dump";
var fullPath=Environment.ExpandEnvironmentVariables(pathToRestore);
var startInfo=new ProcessStartInfo(fullPath,arguments) {
UseShellExecute =false,
//Need this to read the output if needed
RedirectStandardOutput = true;
//Set if needed
WorkingDirectory = binFolder
};
startInfo.EnvironmentVariables["PGPASSWORD"]=password;
var process=Process.Start(startInfo);
Console.WriteLine(process.StandardOutput.ReadToEnd());
推荐阅读
- python - Python中的连通分量标记算法
- ruby-on-rails - 使用 Carrierwave 在 Rails 上上传图像。不更新数据库中的属性
- case - Teradata - 案例 - 分区
- c# - 正则表达式“\d+”选择器一一选择数字
- javascript - 如何正确使用 Vuex 商店?
- python - 用 Python 重新索引
- sapui5 - SAP UI5 - 根据度量将自定义颜色添加到 SAP Viz 图表折线图?
- c++ - 使用 QtConcurrent::run() 修改成员变量?
- python - Python中的合并排序-RuntimeError:超出最大递归深度
- java - jsp表单文本+文件处理