Skip to content

Instantly share code, notes, and snippets.

@GuerrillaCoder
Created October 31, 2018 19:03
Show Gist options
  • Save GuerrillaCoder/fec9c3b421b0b4f0e094b3801f5343a9 to your computer and use it in GitHub Desktop.
Save GuerrillaCoder/fec9c3b421b0b4f0e094b3801f5343a9 to your computer and use it in GitHub Desktop.
public static string RunPsqlCsvImport(string filePath, string user, string dbname, string tableName, bool hasHeaderRow)
{
var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
//WARNING: an entry for below connection must be entered in system pgpass.conf file or import will fail
ProcessStartInfo startInfo = null;
if (isLinux)
{
var args = $"-c \"cat {filePath} | psql -h 127.0.0.1 -U {user} -d {dbname} -w -c 'copy {tableName} from stdin csv header' \" ";
startInfo = new ProcessStartInfo
{
FileName = @"/bin/bash",
Arguments = args,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
};
startInfo.EnvironmentVariables["PGPASSFILE"] = "/var/www/.pgpass.conf";
}
else
{
var args = $"/c cat \"{filePath}\" | psql -h 127.0.0.1 -U {user} -d {dbname} -w -c \"copy {tableName} from stdin {(hasHeaderRow ? "csv header" : "")}\" ";
startInfo = new ProcessStartInfo
{
FileName = @"cmd.exe",
Arguments = args,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
};
}
using (var process = new Process { StartInfo = startInfo })
{
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment