Restore PostgreSQL database in C #

0

I created a .bat to perform the restoration of a database in PostgreSQL and it worked perfectly using the following command:

set PGPASSWORD=postgres123

C:\Progra~1\PostgreSQL.4\bin\pg_restore.exe -i -h localhost -p 5432
-U postgres -c -d dbrestore -v D:\bkp.backup

Now I want to run a bat to do this in C #. I'm running this function:

static void Restore()
{
  Environment.SetEnvironmentVariable("PGPASSWORD", clsConfigBanco.PASSWORD);
  const string exe = @"C:\Progra~1\PostgreSQL.4\bin\pg_restore.exe";
  const string arg = "-i - h localhost - p 5432 - U postgres - c - d dbrestore - v D:\bkp.backup";

  ProcessStartInfo startInfo = new ProcessStartInfo();
  startInfo.FileName = exe;
  startInfo.Arguments = arg;

  try
  {
      using (Process exeProcess = Process.Start(startInfo))
      {
          exeProcess.WaitForExit();
      }
  }
  catch
  {
       // Log error.
  }
}

The problem is that this function does not execute the bat. it just blinks and disappears. how can I do a function to execute this bat? and I have to generate it at runtime because not always the variables will be the same

    
asked by anonymous 27.10.2017 / 20:10

1 answer

1

In the following line:

const string arg = "-i - h localhost - p 5432 - U postgres - c - d dbrestore - v D:\bkp.backup";

was not placed @ before the string, which causes \ to be a special character and the compiler did not show error since \b is a special character.

You can work around this by putting @ before the string, or using \ instead of \

You also have to remove using :

Follow the code below:

static void Restore()
{
  Environment.SetEnvironmentVariable("PGPASSWORD", clsConfigBanco.PASSWORD);
  const string exe = @"C:\Progra~1\PostgreSQL.4\bin\pg_restore.exe";
  const string arg = @"-i - h localhost - p 5432 - U postgres - c - d dbrestore - v D:\bkp.backup";

  ProcessStartInfo startInfo = new ProcessStartInfo();
  startInfo.FileName = exe;
  startInfo.Arguments = arg;

  try
  {
      Process exeProcess = Process.Start(startInfo);
      exeProcess.WaitForExit();
  }
  catch
  {
       // Log error.
  }
}

As I posted in another question, I use psql to perform the restore. Here, I made the following code and it works perfectly:

        Environment.SetEnvironmentVariable("PGPASSWORD", senha);
        const string exe = @"C:\Progra~2\PostgreSQL.1\bin\psql";
        const string arg = @"-U postgres -d db_banco -f D:\Backup\postgresql.dumpall";

        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = exe;
        startInfo.Arguments = arg;

        Process exeProcess = Process.Start(startInfo);

        exeProcess.WaitForExit();
    
27.10.2017 / 20:35