How to escape characters in string variables? (cmd commands) - c#

I have a list of cmd commands I need to run:
sc config winmgmt start= demand
net stop winmgmt /y
rd /S /Q %windir%\\system32\\wbem\\repository
rd /S /Q %windir%\\syswow64\\wbem\\repository
C:\\WINDOWS\\system32\\msiexec.exe /unregserver
C:\\WINDOWS\\system32\\msiexec.exe /regserver
regsvr32 /s C:\\WINDOWS\\system32\\scecli.dll
regsvr32 /s C:\\WINDOWS\\syswow64\\scecli.dll
for %i in (C:\\WINDOWS\\system32\\wbem\\*.dll) do RegSvr32 -s %i
mofcomp C:\\WINDOWS\\system32\\wbem\\rsop.mof
mofcomp C:\\WINDOWS\\system32\\wbem\\en-US\\rsop.mfl
for %i in (C:\\WINDOWS\\syswow64\\wbem\\*.mof) do mofcomp %i
mofcomp.exe C:\\Windows\\system32\\WBEM\\win32_encryptablevolume.mof
sc config winmgmt start= auto
net start winmgmt
I have a txt file in Properties.Resources containing the above commands. And I try to run them like this:
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
Process process = Process.Start(processStartInfo);
if (process != null)
{
foreach(var myString in File.ReadAllLines(Properties.Resources.commandsTXT))
{
process.StandardInput.WriteLine(myString);
}
process.StandardInput.Close();
}
The problem is when I try to run it, I get Unhandled Exception: System.ArgumentException: Illegal characters in path. How could I possibly escape every character in it? As you can see I already tried replacing \s to \\s, but no luck

Related

Remove directory after copy it XCOPY

I'm working with C#, using XCOPY. I have method which copies a full directory into another:
public static void ProcessXcopy(string SolutionDirectory, string TargetDirectory)
{
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
//Give the name as Xcopy
startInfo.FileName = "xcopy";
//make the window Hidden
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
//Send the Source and destination as Arguments to the process
startInfo.Arguments = "\"" + SolutionDirectory + "\"" + " " + "\"" + TargetDirectory + "\"" + #" /e /y /I /B";
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch (Exception exp)
{
throw exp;
}
}
That I want to know if there is a way to remove source directory once it is copied to another directory successfully.
If you want to stick .Net Methods, you can use Directory.Delete in the finally statement . The second parameter indicates to remove the Sub Folder/Files. More details here
Directory.Delete(path,true);
you can use robocopy instead of xcopy
robocopy from_folder to_folder files_to_copy /MOVE
xcopy needs .bat script in order to have same functionality with 1 line of robocopy
Ex:
xcopy /D /V %1 %2
if errorlevel 0 (
del /Q %1
exit /B
)

command line Start.Info.Argument error

I would like run this command with C# :
"%WIX%/bin/heat.exe" dir "C:\Documents and Settings\APP" -gg -sfrag
-cg Appli -out wixappli.wxs
I have this code (Program.cs) :
System.Diagnostics.Process process1 = new System.Diagnostics.Process();
process1.StartInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
process1.StartInfo.Arguments = String.Format("/k \"%WIX%/bin/heat.exe\" dir \"{0}\" -gg -sfrag -cg Appli -out wixappli.wxs ",
#"C:\Documents and Settings\APP");
process1.StartInfo.WorkingDirectory = #"C:\Documents and Settings\test";
process1.StartInfo.CreateNoWindow = true;
process1.StartInfo.ErrorDialog = false;
process1.Start();
Error:
'C:\Program' is not recognized as an internal command or external
command
I don't understand because without C#, it works.
Can you help me ?
Usually, path environments (%windir%, %temp%, etc) uses backslashes (\). try modifying your arguments to use backslashes instead of slashes (\"%WIX% \ bin \ heat.exe\"...

rebuild wmi classes with c#

i am writing c# code to rebuild the wmi classes. i found that it can be done with the help of these command as discussed here :
Regsvr32 %SystemRoot%\System32\wbem\wmidcprv.dll
cd /d %windir%\system32\wbem
for %i in (*.dll) do RegSvr32 -s %i
for %i in (*.exe) do %i /RegServer
i have tried passing these command in cmd and reading the output as :
Process objProcess = new Process();
objProcess.StartInfo.UseShellExecute = false;
objProcess.StartInfo.RedirectStandardOutput = true;
//objProcess.StartInfo.CreateNoWindow = true;
//objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
string cmd1=#"Regsvr32 %SystemRoot%\System32\wbem\wmidcprv.dll";
string cmd2=#"cd /d %windir%\system32\wbem";
string cmd3=#"for %i in (*.dll) do RegSvr32 -s %i";
string cmd4 = #"for %i in (*.exe) do %i /RegServer";
string strFinal = cmd1 + "\n" + cmd2 + "\n" + cmd3 + "\n" + cmd4;
//string cmd1=#"Regsvr32 %SystemRoot%\System32\wbem\wmidcprv.dll cd /d %windir%\system32\wbem for %i in (*.dll) do RegSvr32 -s %i for %i in (*.exe) do %i /RegServer";
objProcess.StartInfo.FileName = string.Format("cmd.exe");
objProcess.StartInfo.Arguments = string.Format(strFinal);
try
{
objProcess.Start();
}
catch
{
throw new Exception("Error");
}
StreamReader strmReader = objProcess.StandardOutput;
string strTempRow = string.Empty;
while ((strTempRow = strmReader.ReadLine()) != null)
{
Console.WriteLine(strTempRow);
}
if (!objProcess.HasExited)
{
objProcess.Kill();
}
Can one share idea how to achieve this by code not manually.
I assume you have problems executing ms-dos commands, not reading the output.
Have you tried creating a batch file with those commands and executing it with system process class?
First of all, create the batch file with those commands and execute it manually. If it's works fine then just execute it as you done before.
System.Diagnostics.Process.Start("wmiBuilder.bat");

Cannot see the results of command line

Previously somebody has asked how to run a command line command in C# from visual studio and the beneath was the answer.
I tried the same intended to call a tool called cccc which can run on command line. But when I run the beneath code I do not get any results and nothing shows wrong.
Stating generally how can we run the same commands from C# as it was in command line and get the same results. Say I call a program (it could be any program that is able to run on command line, for instance, cccc, ccm, and so on) on command line and get some results. How to call the command line and give the arguments so it will call in its turn the cccc or whatever and do the same thing as it was without C#.
string strCmdText;
strCmdText = "/C d: cd D:\\Exercises\\npp52\\PowerEditor\\src && dir /s /b | cccc - --outdir=d:\\myfolder";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
Add 'pause' to the end of your command:
string strCmdText;
strCmdText = "/C d: cd D:\\Exercises\\npp52\\PowerEditor\\src && dir /s /b | cccc - --outdir=d:\\myfolder & pause";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
or redirect console standard output to a stream.
Here need more magic with OutputDataReceived handler
void Main()
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName="cmd.exe";
proc.StartInfo.Arguments = "/c ping 127.0.0.1";
proc.StartInfo.UseShellExecute = false;
proc.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
proc.Close();
}
private void SortOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
// Do what You need with out
Console.WriteLine(outLine.Data);
}
}
Instead of trying to put everything inside a string you could take advantage of the ProcessStartInfo class to better define your arguments
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.WorkingDirectory = "D:\\Exercises\\npp52\\PowerEditor\\src ";
psi.Arguments = "/C dir /s /b | cccc - --outdir=d:\\myfolder"";
psi.WindowStyle = ProcessWindowStyle.Normal;
Process.Start(psi);
Also with the command window open you could see if there are syntax errors in your command
Another problem is that you are not using RedirectStandardOutput, so output is discarded. Take a look at this answer.

adding arguments to process not working?

I got this program written in C# WinForms.
im using system.diagnostic to create a CMD process.
with that cmd i want some arguments but they are not present or working :S
dont know why ?!
NOTE: im not sure how to use more than 1 argument, correct me if im wrong :D
im trying to replicate the "copy /b %filename% lpt1" command....
here is my code:
public void OutputBtn_Process_Click(object sender, EventArgs e)
{
foreach (FileInfo fi in listBox1.Items)
{
Process process1 = new Process();
process1.StartInfo.UseShellExecute = false;
process1.StartInfo.Arguments = "copy /b myfile.txt test.txt";
//process1.StartInfo.LoadUserProfile = true;
process1.StartInfo.FileName = "cmd.exe";
process1.StartInfo.WorkingDirectory = Path.GetDirectoryName(fi.FullName);
process1.Start();
}
}
string strCmdText;
strCmdText= "/C copy /b myfile.txt test.txt";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
Try this
process1.StartInfo.Arguments = "/C \"copy /b myfile.txt LPT1:\"";
The documentation on Windows 7 command-line tool cmd.exe

Categories

Resources