首页 > 解决方案 > 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.

标签: c#.netpostgresqlprocess

解决方案


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());

推荐阅读