Backup and Restore using Postgresql in C#

Asked

Viewed 928 times

1

To back up or re-store a database through a C# application using the Postgresql DBMS, you need to send a command to pg_dump. It is possible to execute it via a select by sending an Executenonquery (the same way it is executed on SQLSERVER?) instead of sending the data to pg_dump?

  • pg_dump is an executable, which must be executed directly on the server or from a terminal informing the server address, so for that, it is likely that it will be necessary to send some executable and postgresql dll together with the application (to run by a terminal)

1 answer

1

There is a question similar to yours, you have tried using this method below? (https://stackoverflow.com/questions/23026949/how-to-backup-restore-postgresql-using-code)

public void PostgreSqlDump(
        string pgDumpPath,
        string outFile,
        string host,
        string port,
        string database,
        string user,
        string password)
    {
        String dumpCommand = "\"" + pgDumpPath + "\"" + " -Fc" + " -h " + host + " -p " + port + " -d " + database + " -U " + user + "";
        String passFileContent = "" + host + ":" + port + ":" + database + ":" + user + ":" + password + "";

        String batFilePath = Path.Combine(
            Path.GetTempPath(),
            Guid.NewGuid().ToString() + ".bat");

        String passFilePath = Path.Combine(
            Path.GetTempPath(),
            Guid.NewGuid().ToString() + ".conf");

        try
        {
            String batchContent = "";
            batchContent += "@" + "set PGPASSFILE=" + passFilePath + "\n";
            batchContent += "@" + dumpCommand + "  > " + "\"" + outFile + "\"" + "\n";

            File.WriteAllText(
                batFilePath,
                batchContent,
                Encoding.ASCII);

            File.WriteAllText(
                passFilePath,
                passFileContent,
                Encoding.ASCII);

            if (File.Exists(outFile))
                File.Delete(outFile);

            ProcessStartInfo oInfo = new ProcessStartInfo(batFilePath);
            oInfo.UseShellExecute = false;
            oInfo.CreateNoWindow = true;

            using (Process proc = System.Diagnostics.Process.Start(oInfo))
            {
                proc.WaitForExit();
                proc.Close();
            }
        }
        finally
        {
            if (File.Exists(batFilePath))
                File.Delete(batFilePath);

            if (File.Exists(passFilePath))
                File.Delete(passFilePath);
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.