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%
Related
I am trying to pass 2 arguments to the Process.start in c# and part of the string has to be a string var that is built from the input of the user.
This code works fine when I use a simple folder path but my path is determined by the user to the process.StartInfo.Arguments must = "-format mp4 -outfolder " + myVar.
I cannot get this to work.
Process process = new Process();
process.StartInfo.FileName = #"C:\Program Files (x86)\NCH Software\Prism\Prism.exe";
process.StartInfo.Arguments = "-format mp4 -outfolder C:/users/john";
process.Start();
The expected results would be the prism opening screen having the mp4 format automatically selected (which works fine) and the output folder is set by the variable. that part of the argument is being ignored and a default folder is being set up.
I think in your case you have to use \" \" between the var.
process.StartInfo.Arguments = "-format mp4 -outfolder #\" " + myVar + "\""
Follow this site and you can find more information.
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.arguments?view=netframework-4.8
or else try,
string a = "aaa";
string b = "bbb";
Process.Start(#"something.exe ", "#"+ a + " " + b );
I'm currently working with reg.exe and I'm creating a process with reg.exe as the Process.FileName.
When I try to execute reg.exe like following
REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS D:\\Backups\\Test.reg
everthing works fine.
But as soon as I try to execute it like this
REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS D:\\Backups\\Backup folder 1\\Test.reg
nothing happens - and I know why! The target path isn't put in quotes. As soon as I do that everything works fine again.
My problem now is that I'm handling all my file and folder paths as instances of DirectoryInfo. When I pass the path with quotes as a string, e.g. like that
DirectoryInfo targetFolder = new DirectoryInfo("\"D:\\Backups\\Backup folder 1\\Test.reg\"")
I instantly receive an exception telling me that the given path's format is not supported.
Is there any way to put the path in quotes and still work with DirecotryInfo?
I really need to put my path in quotes - otherwise the command won't work.
Here's some example code:
DirectoryInfo backupPath = new DirectoryInfo("D:\\Backups\\Backup folder 1\\Test.reg");
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "reg.exe";
startInfo.CreateNoWindow = true;
startInfo.Arguments = "REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS " + backupPath.FullName;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
When I run this code, nothing happens - nor errors or exceptions. The .reg file itself isn't created either.
When I try to run it like this
DirectoryInfo backupPath = new DirectoryInfo("\"D:\\Backups\\Backup folder 1\\Test.reg\"");
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "reg.exe";
startInfo.CreateNoWindow = true;
startInfo.Arguments = "REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS " + backupPath.FullName;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
I'm getting a System.NotSupportedException telling me "The given path's format is not supported." But I actually need to put the path in quotes - otherwise the command itself won't work...
You are adding quotes in the wrong place: constructor of DirectoryInfo will strip them anyway to normalize the path, so you can skip adding them:
var backupPath = new DirectoryInfo("D:\\Backups\\Backup folder 1\\Test.reg");
You can force quotes around the path when you add backupPath.FullName to the arguments, like this:
startInfo.Arguments = "REG EXPORT HKLM\SOFTWARE\Intel\IntelAMTUNS \"" + backupPath.FullName + "\"";
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 a simple problem but I don't know how to handle this. That is: I have a simple batch file that remove all file in the folder (for example). I can run it in anywhere but I want to exec it by a application by C#. Everything is allright If the project folder doesn't contains spaces ("Example: C:\Project Test\test.bat" will be error" but "C:\ProjectTest\test.bat" is done").
Below is my source code to run (I say it again: It only error if project folder contain space in folder names). Not error when run file batch if project folder not have space.
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.Arguments = "D:\\prepare.bat";
myProcess.StartInfo.WorkingDirectory = "D:\\";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
//myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;
string myString = myStreamReader.ReadLine();
MessageBox.Show(myProcess.StartInfo.Arguments + " " + myString);
myProcess.WaitForExit();
Thanks you.
Try putting script path in quotes:
myProcess.StartInfo.Arguments = "\"D:\\Project Test\\prepare.bat\"";
Enclose your arguments in quotes like this:
myProcess.StartInfo.Arguments = "\"C:\\Project Test\\test.bat\""
or
myProcess.StartInfo.Arguments = #"\"C:\Project Test\test.bat\""
When passed to cmd the arguments must be quoted.
instead of "C:\Project Test\test.bat" use "\"C:\Project Test\test.bat\""
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