SafeDispatch/SafeMobileLIB_DLL/DBbackup.cs

102 lines
3.5 KiB
C#
Raw Permalink Normal View History

2024-02-22 16:43:59 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;
namespace SafeMobileLib
{
public class DBbackup
{
private string dbServer, dbPort,dbUser, dbDbname;
public DBbackup(string dbUser, string dbName,string dbServ)
{
this.dbUser = dbUser; this.dbDbname = dbName; this.dbServer = dbServ;
}
public bool performBackupPostgres(string path, string postgresPath)
{
try
{
if (path == "")
{
path = "backups";
}
DateTime backupTime = DateTime.Now;
string bTime = backupTime.ToString("yyyy_MM_dd_HH_mm");
String tmestr = "";
if (!Directory.Exists("backups"))
Directory.CreateDirectory("backups");
tmestr = path + "\\" +bTime+ ".tar";
Console.WriteLine("Backup db to:" + tmestr);
ProcessStartInfo proc = new ProcessStartInfo();
string cmd = string.Format("--username={0} --file=\"{1}\" --format=c --create --host={2} {3} ",
dbUser, tmestr,dbServer, dbDbname);
Console.WriteLine("backup command:" + cmd);
try
{
postgresPath += "pgsql\\bin\\";
proc.FileName = postgresPath + "pg_dump.exe";
proc.RedirectStandardInput = false;
proc.RedirectStandardOutput = false;
proc.Arguments = cmd;
proc.UseShellExecute = false;
Process p = Process.Start(proc);
p.WaitForExit();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
return false;
}
return true;
}
catch (IOException ex)
{
SM.Debug("Disk full or other IO error , unable to backup!" + ex.ToString());
return false;
}
}
public bool performRestorePostgres(string filepath, string postgresPath)
{
try
{
Console.WriteLine("restore db from:" + filepath);
ProcessStartInfo proc = new ProcessStartInfo();
string cmd = string.Format("-c --dbname={0} --username={1} --host={2} \"{3}\"",
dbDbname, dbUser,dbServer, filepath);
Console.WriteLine("restore command:"+cmd);
try
{
postgresPath += "pgsql\\bin\\";
proc.FileName = postgresPath + "pg_restore.exe";
proc.RedirectStandardInput = false;
proc.RedirectStandardOutput = false;
proc.Arguments = cmd;
proc.UseShellExecute = false;
Process p = Process.Start(proc);
p.WaitForExit();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
return false;
}
return true;
}
catch (IOException)
{
return false;
}
}
}
}