Search code examples
c#postgresqlpg-dump

How to pass password StandardInput to pg_dump?


I'm creating Process to run pg_dump.exe in C#

var processStartInfo = new ProcessStartInfo
{
    Arguments = @"-U postgres -W -f D:\postgres\test123_dump.sql postgres",
    CreateNoWindow = true,
    FileName = @"C:\PostgreSQL\bin\pg_dump.exe",
    UseShellExecute = false,
    WindowStyle = ProcessWindowStyle.Hidden,
    RedirectStandardInput = true
};

Process process = new Process() { StartInfo = processStartInfo, EnableRaisingEvents = true };

process.Start();

using( StreamWriter sw = process.StandardInput)
{
    sw.WriteLine("123"); // test password
};

It will run pg_dump.exe, it will show prompt to pass the password, but StreamWriter seems to not work for some reason.


Solution

  • You could use this string to put your authentication info directly in argument list

    var processStartInfo = new ProcessStartInfo
        {
            Arguments = @"--dbname=postgresql://user_name:pass_word@Localhost:5432/bd_name_to_save -F c -b -f output_bd_name",
            CreateNoWindow = true,
            FileName = @"C:\PostgreSQL\bin\pg_dump.exe",
            UseShellExecute = false,
            WindowStyle = ProcessWindowStyle.Hidden,
            RedirectStandardInput = true
        };
        
        Process process = new Process() { StartInfo = processStartInfo, EnableRaisingEvents = true };
        
        process.Start();