I am trying to execute a batch file which directs 7zip to compress a directory. The batch file is working fine when I run it by 'double-clicking' the file or if I try to run it in the command Prompt. But I am having problem while I am try to execute the file through a C# application. Below is my code in C#.
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
path = path.Substring(0, path.IndexOf("Debug") + 6) + "Scripts";
String EnvironmentPath = System.Environment
.GetEnvironmentVariable("path",
EnvironmentVariableTarget.Machine);
string[] varList = EnvironmentPath.Split(';');
string enviVar= varList.First(x=>x.Contains("7-Zip"));
Process proc = new Process();
proc = new Process();
proc.StartInfo.WorkingDirectory = path;
proc.StartInfo.Arguments = enviVar;
proc.StartInfo.FileName = "Script_To_BackUp_DB.bat";
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
The value in path variable is : D:\Projects\Common\common\Common\Utilities\Utilities\bin\Debug\Scripts.
If I remove the "proc.StartInfo.UseShellExecute = false" line, then batch will execute and close with an exception stating 7z is not recognized as Internal or external command. And I have already set the path in Environment Variable.
The batch file code is:
set backup_dir=C:\Users\FU386DKH\Desktop\Card logs\
set db_dir=D:\Projects\Projects\db\
:: set dt string in dd_mm_yy_HH_MM_SS format
set dt=%Date:~0,2%_%Date:~3,2%_%Date:~6,4%_%Date:~0,2%_%Date:~3,2%_%Date:~6,2%
:: compress folder
7z a -tzip "%backup_dir%_%dt%.zip" "%db_dir%" -ssw
set backup_dir=C:\Users\FU386DKH\Desktop\ConsoleApplication2\
set db_dir=D:\Projects\NPCI\db\
:: set dt string in dd_mm_yy_HH_MM_SS format
set dt=%Date:~0,2%_%Date:~3,2%_%Date:~6,4%_%Date:~0,2%_%Date:~3,2%_%Date:~6,2%
:: compress folder
::Setting the path with the location of 7zip exe file.
set PATH=%PATH%;C:\Program Files\7-Zip\
7z a -tzip "%backup_dir%_%dt%.zip" "%db_dir%" -ssw
Related
This is my codes
ProcessStartInfo ps = new ProcessStartInfo();
ps.FileName = #"C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python37\\python.exe";
ps.WindowStyle = ProcessWindowStyle.Normal;
ps.Arguments = string.Format("C:\\Users\\Admin\\Downloads\\order.py-master\\order.py-master\\order.py -a 999 -b ",this.textbox.Text);
Process.Start(ps);
There is a function that I am using in my project that is called "RunBat" which runs bat files, but can really work on any file extension such as .py as well.
RunFile.RunBat("Directory/To/Script.py", true);
The way this was possible was by using Process.Start() and setting the path into the base directory, so all you would need to do is input the rest of the directory that leads to the file.
public static int RunBat(string currentFile, bool waitexit)
{
try
{
string path = AppDomain.CurrentDomain.BaseDirectory;
Process process = new Process();
process.StartInfo.FileName = path + currentFile;
process.Start();
if (waitexit == true)
{
process.WaitForExit();
}
return 0;
}
catch
{
return 1;
}
}
The bool waitexit is an optional setting to keep the prompt open while it does it's commands. You can turn this off by using false.
If this fails to work, and you are trying to run a file that is NOT added as a resource in the code, then you would want to change the string path = AppDomain.CurrentDomain.BaseDirectory; to C:\\.
What this will do is instead of starting from the base directory of the application, it will start from the C:\ drive, and then you would continue the rest of the directory in currentFile.
I have to rename multiple files on my server. For this I make a c# project in visual studio. (side info: this project has to do other stuff too)
Now I try to call a batch file from that project. This batch file has to rename a file using the old and the new filename.
Here is the code from the batch file:
#echo off
set FILENAME_OLD="%~1"
set FILENAME_NEW="%~nx2"
ren %FILENAME_OLD% %FILENAME_NEW%
set error=%errorlevel%
echo %error%
This is the code in my c# project:
process.StartInfo.FileName = location;
process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\"", oldfilename, newfilename);
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
result = process.StandardOutput.ReadLine();
As result I always get 1. Which means that "ren" didn't work. What am i doing wrong here?
The filenames are all in a structure like this in my c# project: #"C:\test\test\test.bat"
EDIT:
I came somewhat closer to a solution. The problem was that I cant pass the double quotes as an argument. I need those double quotes as some of my filenames contain spaces.
How can I pass those filenames correctly to that batchfile?
I managed to fix the problem with on a in my opinion 'dirty' way:
//I changed newfilename so it's only the filename with extention and not the full path anymore.
string text = "\"" + oldfilename+ "\"" + " " + "\"" + newfilename;
System.IO.File.WriteAllText(#"c:\test\test.txt", text);
process.StartInfo.FileName = location;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
result = process.StandardOutput.ReadLine();
As you can see I wrote the arguments to a txt file so the quotes will be escaped.
The batchfile now is as simple as this:
set /p arguments=<c:\test\test.txt
ren %arguments%
echo %errorlevel%
I read many post, from them there is this one
c# - Opening the terminal process and pass commands?
I do the exact same thing in my code
Process proc = new System.Diagnostics.Process ();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
where command = export DISPLAY=:0.0
and it goes to my catch, "pplicationName='/bin/bash', CommandLine='-c " cd .. "', CurrentDirectory='', Native error= The system cannot find the file specified."
what do I do differently? even if I try to juste set command = "cd .." it doesn't work
You should probably try setting the full path the executable.
proc.StartInfo.FileName = "C:/SOMEPATH/Bash.exe";
I'm assuming as you are specifying a relative path, it's not resolving it. Possibly because you aren't setting a working directory for the process so it's current dir and the current dir you think it has, are different.
I have an exe file which I run through windows command prompt and give command line arguments. I went through this post and ran the following command:
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
But all it did, is to give me resource files located in WindowsFormsApplication1\obj\Debug folder
I went through this post but it tells on how to execute the exe directly without the running it from cmd.
I even tried the following command:
string path = Path.Combine(Path.GetTempPath(), "MyApplication.exe");
It worked but after clearing my C:\Users\UserName\AppData\Local\Temp folder the application started giving an error.
I even tried the following command:
global::ApplicationName.Properties.Resources.MyApplication
but it gives byte[] and not the path to the application.
All I want to know is how to run the application which is embedded in my resources so that I can successfully execute the following command:
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/K " + MyApplication+" Argument "+Path1+" "+Path2 ,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadToEnd();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(resultFile))
{
file.WriteLine(line);
}
}
Extract the resource into a file in the filesystem and then run it.
byte[] fileContents = ApplicationName.Properties.Resources.MyApplication;
File.WriteAllBytes("MyApplication.exe", fileContents);
Now you can run the file using MyApplicaton.exe as path.
I'm calling a .bat file to XCOPY a folder. Is there anyway to pass the file name and the destination into the batch file?
My .bat file
XCOPY %1 %2
pause
The code I'm using to call the .bat is this:
process.Start(#"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat");
I've tried this code
process.Start(#"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat" , copyfrom copyto);
As i've used that before for shutting down my comp, but it doesn't work with this.
Thanks
Update
process.StartInfo.FileName = #"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat";
process.StartInfo.Arguments = copyFrom.ToString();
process.StartInfo.Arguments = copyTo.ToString();
process.Start();
That is the code I'm using but It doesn't work. I'm getting this from the XCOPY screen:
So it doesn't look like its taking the full file paths. copyto and copyfrom are variables that contain the paths.
UPDATE
Using azhrei's code:
String batch = #"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat";
String src = #"C:\Tricky File Path\Is Here\test1.txt";
String dst = #"C:\And\Goes Here\test2.txt";
String batchCmd = String.Format("\"{0}\" \"{1}\" \"{2}\"", batch, src, dst);
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = String.Format("/k \"echo {0}\"", batchCmd);
process.Start();
I'm getting this output:
Which isn't actually copying the file.
you can use Arguments property
Process proce = new Process();
proce.StartInfo.FileName = "yourfile.exe";
proce.StartInfo.Arguments = ..;
proce.Start();
Article : http://www.c-sharpcorner.com/UploadFile/jawedmd/xcopy-using-C-Sharp-to-copy-filesfolders/
Replace it with this,
var process = new Process();
process.StartInfo.FileName = #"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat";
process.StartInfo.Arguments = // my arguments
process.Start();
A better option would be to replace what your XCOPY.BAT file is doing with the equivalent calls in System.IO (you get error handling then).
You're starting a batch file - you'll need to use cmd.exe
Surround each argument with " (needed if the argument has spaces).
String batch = #"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat";
String src = #"C:\Tricky File Path\Is Here\test1.txt";
String dst = #"C:\And\Goes Here\test2.txt";
String batchCmd = String.Format("\"{0}\" \"{1}\" \"{2}\"", batch, src, dst);
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = String.Format("/k \"{0}\"", batchCmd);
process.Start();
If your batch file literally xcopies and nothing else, then you can just replace cmd.exe with xcopy.exe and remove the /k + batch.
Pass it parameters?
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true