I am trying to export a database from c# using mysqldump.
When I run it i get this message: Unknown database 'mysqldump' when selecting the database.
I can't find the solution.
public static void mysqlBackup()
{
try
{
//string time = DateTime.Now.ToString("dd-MM-yyyy");
Log.Info("Starting MySQL dump");
Process MySqlDump = new Process();
MySqlDump.StartInfo.FileName = #"mysqldump.exe";
MySqlDump.StartInfo.UseShellExecute = false;
MySqlDump.StartInfo.Arguments =
"mysqldump -uroot -p******** b3 >"+
" C:/Users/Administrator/Documents/temp/backups/backup.sql";
MySqlDump.StartInfo.RedirectStandardInput = false;
MySqlDump.StartInfo.RedirectStandardOutput = false;
MySqlDump.Start();
MySqlDump.WaitForExit();
MySqlDump.Close();
Log.Info("Successfull created");
}
catch (IOException ex)
{
Log.Error("Unable to write the database file" + ex.ToString());
}
}
I tried to remove the mysqldump from the arguments kinda the same problem.
The redirection operator > is not an argument to mysqldump. When you execute it on the command line, it's being interpreted by the command line itself, not by mysqldump. You have two choices here:
Use the --result-file option as others have mentioned
Capture the stdout of the process and do what you like with the output by setting the RedirectStandardOutput property of StartInfo to be true. After this, you can read from the StandardOutput stream of the process.
I think you need to specify the name of the database you want to dump as the first argument. Thanks to nathan it goes after --databases at the end.
MySqlDump.StartInfo.Arguments = "-u root -p *** database_name --result-file [path]\backup.sql";
You don't need to specify mysqldump again in the command either (not that it should make much difference).
The Mysql documentation states there are 3 ways to use the mysqldump command:
shell> mysqldump [options] db_name [tbl_name ...]
shell> mysqldump [options] --databases db_name ...
shell> mysqldump [options] --all-databases
Ensure the command works fine via your command line. If it does that execute that command directly within your code. If that works then start extracting your arguments and replacing them with your own parameters within code.
Basically you want to get as basic as possible and work back up from there.
If the file works on the command line, try this:
using (Process p = new Process())
{
p.StartInfo.FileName = #"mysqldump.exe -u root -p *** --database b3 -r test.sql"; <~~~ note the change here
p.Start();
p.WaitForExit();
}
The file will be dumped to your project folders bin/debug or bin/release folder unless you change that code.
Here is your edited method:
public static void mysqlBackup()
{
try
{
//string time = DateTime.Now.ToString("dd-MM-yyyy");
Log.Info("Starting MySQL dump");
using(Process MySqlDump = new Process()
{
MySqlDump.StartInfo.FileName = #"mysqldump.exe";
MySqlDump.StartInfo.UseShellExecute = false;
MySqlDump.StartInfo.Arguments = "-uroot -p******** b3 --result-file=C:/Users/Administrator/Documents/temp/backups/backup.sql";
MySqlDump.StartInfo.RedirectStandardInput = false;
MySqlDump.StartInfo.RedirectStandardOutput = false; //You can redirect this as mention in other answers
MySqlDump.Start();
MySqlDump.WaitForExit();
MySqlDump.Close();
}
Log.Info("Successfully created");
}
catch (IOException ex)
{
Log.Error("Unable to write the database file" + ex.ToString());
}
}
Related
I've got a code to create a backup copy from a query, this query takes the older registers from a year in the past and saves them into a *.sql file. But the problem that I found is when I open the .sql file and it's empty. I've tried the query in command prompt and it works perfectly.
I'm new using mysql and I have read these posts to create my code (and looking for answers):
Backing up Database in MySQL using C#
C# and mysqldump
How to take backup of MySQL Database
try
{
string strBackupFileName = GetBackUpFileName();
StreamWriter strBackupFile = new StreamWriter(strBackupFileName);
ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.FileName = #"c:\Users\current.user\source\xampp\mysql\bin\mysqldump.exe";
psInfo.RedirectStandardInput = false;
psInfo.RedirectStandardOutput = false;
psInfo.Arguments = "- u root -h localhost --databases --hex-blob -n -t dashboard --tables dashboard.backup --where='updated_at < NOW() - INTERVAL 365 DAY'";
psInfo.UseShellExecute = false;
psInfo.RedirectStandardOutput = true;
Process backup_process = Process.Start(psInfo);
string stdout;
stdout = backup_process.StandardOutput.ReadToEnd();
strBackupFile.WriteLine(stdout);
backup_process.WaitForExit();
strBackupFile.Close();
backup_process.Close();
MessageBox.Show("Backup done at file:" + strBackupFileName);
}
catch (Exception ex)
{
MessageBox.Show("Error during the backup: \n\n" + ex.Message);
}
When I run the program I see that mysqldump doesn't "wait" to do the process (when I do it manually, it takes at least 25-30 seconds), it opens a command prompt window and closes immediately.
The solution was simple, in:
psInfo.Arguments = "- u root -h localhost --databases --hex-blob -n -t dashboard --tables dashboard.backup --where='updated_at < NOW() - INTERVAL 365 DAY'";
only i must to delete the space between "-" and "u".
I'm calling a python script from a C# tool. I based my code on this post. I use ProcessStartInfo to start python and pass a .py file and some argument to it. The code runs fine when the .py, CreateAssessorMap.py, file is on the c drive but not when it is on a mapped network drive. No error is thrown but no python code is executed as far as I can see. If I manually do the same operation from the command line it runs fine.
The code below the first procStartInfo.Arguments will fail as CreateAssessorMap.py is on a network drive. The commented out line below it would work as the script is on the C drive.
private void btnPrint_Click(object sender, EventArgs e)
{
try
{
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.FileName = "python";
procStartInfo.Arguments = string.Format("{0} {1} {2}", #"D:\Map_Generate_Scripts\CreateAssessorMap.py", this.txtSheet.Text, txtDestinationFolder.Text);
//procStartInfo.Arguments = string.Format("{0} {1} {2} ", #"C:\Projects\Map_Generate_Scripts\CreateAssessorMap.py", this.txtSheet.Text, txtDestinationFolder.Text);
procStartInfo.UserName = null;
procStartInfo.UseShellExecute = false;
procStartInfo.RedirectStandardOutput = true;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now you create a process, assign its ProcessStartInfo, and start it.
using (Process process = Process.Start(procStartInfo))
{
using (System.IO.StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
catch (Exception ecpt)
{
Console.WriteLine(ecpt.Message);
}
this.Parent.Hide();
}
Edit
I added some error handling and the python code is failing with the message that the .py file cannot be found.
python: can't open file 'D:\Map_Generate_Scripts\CreateAssessorMapCreateAssessorMap.py': [Errno 2] No such file or directory
I know it exists since I can run the file from the command line with the same arguments. So it seems that when I run from C# the python process can't find the d drive.
I assume that when it runs from a network drive it takes longer and your program does not wait for Python script's completion. I suggest adding proces.Wait() before reading the output stream.
As stated in the comments, the solution for Dowlers was to use the full path instead of the mapped network drive.
Change
#"D:\Map_Generate_Scripts\CreateAssessorMap.py"
To
#"\\[network path]\Map_Generate_Scripts\CreateAssessorMap.py"
I am invoking Powershell from C# to gather some information and using Out-File to send it to a text file. Then I need to read the lines from said file and do stuff with the data inside of C#.
string MyCommand = "-Command &{ get-process | Out-File C:\\MyFile.txt}";
ProcessStartInfo MyProcInfo = new ProcessStartInfo();
MyProcInfo.FileName = "powershell.exe";
MyProcInfo.Arguments = MyCommand;
Process MyProcess = new Process();
MyProcess.StartInfo = MyProcInfo;
MyProcess.Start();
MyProcess.WaitForExit();
try
{
var lines = File.ReadLines(#"C:\MyFile.txt");
(etc)
}
catch (Exception Ex)
{
MessageBox.Show(Ex.ToString());
}
So when it tries to open the text file I am getting a
"File Not Found"
exception. The file IS being written every time, so I am assuming that there is a timing thing going on which is why I am using WaitForExit. But it is still not able to 'find' the file.
Why don't you write the file with C# instead of PowerShell?
You can leverage the Diagnostics.Process .NET class (here's a PowerShell example)
$proc = [Diagnostics.Process]::Start($exe, $arguments)
$proc.WaitForExit()
I can't tell you what is wrong but I can give you some tips to troubleshoot.
After MyProcess.WaitForExit()
add a test for the file's existence.
if (File.Exists(#"C:\Myfile.txt"))
{
... file process code here....
}
Get rid of the hardcoded file names and use variables instead.
string filename = #"C:\MyFile.txt";
string MyCommand = "-Command &{ get-process | Out-File " & filename &
"}";
then when you want to access the file use:
if (File.Exists(filename))
{
...process the file.
}
The advantage of this is that you are 100% guaranteed that you are using exactly the same filename in all places.
Add a breakpoint after MyProcess.WaitForExit();
Then, when the execution stops, navigate to the file and ensure that it is physically there AT THAT TIME and ensure that it is not locked by the program. For example, try to rename it or delete it. If it is still locked you should not be able to do either of those things. Also, most current versions of Windows have someplace that you can check for open files. If you tell me what OS you are running I might be able to tell you how to check that.
One more thing: another poster mentioned Windows Redirection. I personally have never had that happen when the file was explicitly fully qualified.
HTH,
John
Hello!
You can try to do something like this:
maybe it help for you
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string MyCommand = "-Command &{ if (!(Test-Path 'c:\\test')) {md 'c:\\test'; get-process | Out-File c:\\test\\MyFile.txt}}";
ProcessStartInfo MyProcInfo = new ProcessStartInfo();
MyProcInfo.FileName = "powershell.exe";
MyProcInfo.Arguments = MyCommand;
Process MyProcess = new Process();
MyProcess.StartInfo = MyProcInfo;
MyProcess.Start();
MyProcess.WaitForExit();
try
{
var lines = File.ReadLines(#"c:\test\MyFile.txt");
foreach (var ln in lines) {
Console.WriteLine(ln);
Console.ReadKey();
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
Console.ReadKey();
}
}
I would like to execute a cqlsh copy command from c# source code. I would like to execute a Python script, which exists under the folowing path:
C:\Program Files\DataStax Community\python\python.exe" "C:\Program Files\DataStax Community\apache-cassandra\bin\cqlsh.py
That will give me this screenshot:
Once in cqlsh, I can then run the command "copy emp to emp.csv"
The idea, is that I would like to execute all this from c# code. Here is what I did:
try
{
Process p = new Process(); // create process (i.e., the python program
p.StartInfo.FileName = #"C:\Python27\python.exe";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false; // make sure we can read the output from stdout
p.StartInfo.Arguments = #"C:\Program Files\DataStax Community\apache-cassandra\bin\cqlsh.py" + " " + "-e copy key_space.emp to 'D:/emp.csv'"; // start the python program with two parameters
p.Start(); // start the process (the python program)
p.WaitForExit();
}catch(Exception ex)
{
Console.WriteLine(ex.Message);
string strError = ex.Message;
}
There is no exception caught but also there is nothing happened in term of result.
Any help would be appreciated .
I'm pretty sure your problem is with this line:
bin\cqlsh.py" + " " + "copy emp to D:/emp.csv";
If you were to run this from the command line, cqlsh would require the -e flag to execute a command. In Windows it'd look something like this (assuming a keyspace name of "your_keyspace":
python bin\cqlsh.py -e "copy your_keyspace.emp to d:\emp.csv"
So to actually call that from your process, you would either have to escape the double quotes or just use single quotes:
bin\cqlsh.py" + " " + "-e 'copy your_keyspace.emp to d:\emp.csv'";
Where am I going wrong with this? It's like the arguments are not even getting executed, it just opens the command prompt, and that's it. The "results" (StandardOutput) is exactly what shows up when you just open a new command prompt....says Microsoft Windows [Version 6.1.7600] Copyright...blah then the path where the command prompt is starting from.
Anyway, here's the code that I have:
private static void ExecuteProcess(string processFile, string processArguments)
{
ProcessStartInfo psi = new ProcessStartInfo(processFile, processArguments);
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
//psi.CreateNoWindow = true;
Process p = new Process();
p.StartInfo = psi;
try
{
Cursor.Current = Cursors.WaitCursor;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Cursor.Current = Cursors.Default;
if (p.ExitCode == 0)
MessageBox.Show(output, "Results");
else
throw new Exception(p.StandardError.ReadToEnd());
}
catch (Exception ex)
{
Cursor.Current = Cursors.Default;
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
p.Dispose();
}
}
processFile is equal to "cmd.exe"
processArguments is equal to:
csvde -s {servername} -f {filename} -d OU=MyOU,DC=dmz,DC=lan -r "(objectClass=organizationalUnit)" -n
Any help as to why the "arguments" aren't getting executed would be great!
Edit:
One thing I've found so far, Chris's suggestion about the permissions is true, I needed to set:
psi.Verb = "runas";
But when executing the process it didn't look like there was a username associated with the process, so I added this line as well:
psi.UserName = Environment.UserName;
Now I'm getting "the stub received bad data"...
From the docs:
Cmd
Starts a new instance of the command interpreter, Cmd.exe. Used
without parameters, cmd displays Windows XP version and copyright
information.
Syntax cmd [[{/c|/k}] [/s] [/q] [/d] [{/a|/u}] [/t:fg]
[/e:{on|off}] [/f:{on|off}] [/v:{on|off}] string] Top of page
Parameters
/c : Carries out the command specified by string and then
stops.
So you need to:
Pass the full path to the EXE or
Set the working directory to the directory containing the exe
then
Make processFile == "[]csvde.exe", and remove it from processArguments, or
Prepent "/c \"" and append "\"" to processArguments.
I finally got back to working on this and figured out how to get this to work.
I had to specifically set the Username, Password, and Domain of the Process.ProcessStartInfo in order for the process to execute.