Executing line commands arguments with 2 variables problem c# - c#

I am trying to open my .exe "application" with 2 arguments. When I write the command line myself without " " it don't want to work. When I write the command line using "C:/Path" "A" "B" it does work.
How do I fix this?
if(element.SaveType == "1")
{
DirectoryInfo srcDir = new DirectoryInfo((string)element.SourcePath);
DirectoryInfo dstDir = new DirectoryInfo((string)element.DestinationPath);
if (element.didEncrypt == true)
{
if (Directory.GetFiles(srcDir.FullName, ((string)element.EncryptExt)).Length == 0)
{
string pat = System.IO.Path.Combine(#"C:\Users\Client Fractal\source\repos\CryptoSoft\CryptoSoft\bin\Debug\netcoreapp3.0\CryptoSoft.exe");
Process p = new Process();
p.StartInfo.FileName = pat;
p.StartInfo.Arguments = srcDir.FullName + dstDir.FullName; // source / target;
Console.WriteLine(p.StartInfo.Arguments);
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
}
}
}

Command-line arguments are space-character delimited, so you'd need to insert a space character or your arguments will end up getting squashed together.
p.StartInfo.Arguments = srcDir.FullName + " " + dstDir.FullName;
But of course, if either srcDir.FullName or dstDir.FullName contain space characters of their own (and FullName suggests they do), you will need to surround them with double quote characters.
p.StartInfo.Arguments = "\"" srcDir.FullName + "\" \"" + dstDir.FullName + "\"";

Related

using poweriso cmd commands from c sharp code

I am making a C# program that will make input file an .iso file.
For example if we write C:\Users\User\Desktpo\a.txt in the textbox that I created and give a destination path for example C:\ it has to create an iso file name a in C:\.
So I downloaded PowerISO and learn about piso.exe then I made some other research about using Process.Start(); in C# so I write these lines of code:
string str = " create -o " + TextBox1.Text + ".iso -add " + TextBox2.Text + "//" ;
Process process = new Process();
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "\"C:\PowerISO\piso.exe\"";
process.StartInfo.Arguments = str;
process.Start();
But this doesn't work.
Why?
EDIT: I am making an winform using Visual Studio 2017.
Please Note that
C:\PowerISO\piso.exe\
is not a valid C# path, the "\" before the P and the p is an escape indicater.
Either Add verbatim operator "#" before or escape it properly
edit:
In addition, you are adding extra double quotes to the FileName property.
You can check if the path is correct by asserting the file path with File.Exists method
Console.WriteLine(File.Exists(#"C:\PowerISO\piso.exe") ? "File exists." : "File does not exist.");
e.g
string str = " create -o " + TextBox1.Text + ".iso -add " + TextBox2.Text + "//" ;
Process process = new Process();
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.FileName = #"C:\PowerISO\piso.exe";
process.StartInfo.Arguments = str;
process.Start();
edit:
Verbatim operator will work, but escaping is better in my opinion.
string str = " create -o " + TextBox1.Text + ".iso -add " + TextBox2.Text + "//" ;
Process process = new Process();
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "C:\\PowerISO\\piso.exe";
process.StartInfo.Arguments = str;
process.Start();

Trying to run same command in command prompt not working

I am making a program that seeks out secured PDFs in a folder and converting them to PNG files using ImageMagick. Below is my code.
string WorkDir = #"C:\Users\rwong\Desktop\TestFiles";
Directory.SetCurrentDirectory(WorkDir);
String[] SubWorkDir = Directory.GetDirectories(WorkDir);
foreach (string subdir in SubWorkDir)
{
string[] filelist = Directory.GetFiles(subdir);
for(int f = 0; f < filelist.Length; f++)
{
if (filelist[f].ToLower().EndsWith(".pdf") || filelist[f].EndsWith(".PDF"))
{
PDFReader reader = new Pdfreader(filelist[f]);
bool PDFCheck = reader.IsOpenedWithFullPermissions;
reader.CLose();
if(PDFCheck)
{
//do nothing
}
else
{
string PNGPath = Path.ChangeExtension(filelistf], ".png");
string PDFfile = '"' + filelist[f] + '"';
string PNGfile = '"' + PNGPath + '"';
string arguments = string.Format("{0} {1}", PDFfile, PNGfile);
ProcessStartInfo startInfo = new ProcessStartInfo(#"C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe");
startInfo.Arguments = arguments;
Process.Start(startInfo);
}
}
}
I have ran the raw command in command prompt and it worked so the command isn't the issue. Sample command below
"C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe" "C:\Users\rwong\Desktop\TestFiles\Test_File File_10.PDF" "C:\Users\rwong\Desktop\TestFiles\Test_File File_10.png"
I looked around SO and there has been hints that spaces in my variable can cause an issue, but most of those threads talk about hardcoding the argument names and they only talk about 1 argument. I thought adding double quotes to each variable would solve the issue but it didn't. I also read that using ProcessStartInfo would have helped but again, no dice. I'm going to guess it is the way I formatted the 2 arguments and how I call the command, or I am using ProcessStartInto wrong. Any thoughts?
EDIT: Based on the comments below I did the extra testing testing by waiting for the command window to exit and I found the following error.
Side note: I wouldn't want to use GhostScript just yet because I feel like I am really close to an answer using ImageMagick.
Solution:
string PNGPath = Path.ChangeExtension(Loan_list[f], ".png");
string PDFfile = PNGPath.Replace("png", "pdf");
string PNGfile = PNGPath;
Process process = new Process();
process.StartInfo.FileName = #"C:\Program Files\ImageMagick-6.9.2 Q16\convert.exe";
process.StartInfo.Arguments = "\"" + PDFfile + "\"" +" \"" + PNGPath +"\""; // Note the /c command (*)
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
string err = process.StandardError.ReadToEnd();
Console.WriteLine(err);
process.WaitForExit();
It didn't like the way I was formatting the argument string.
This would help you to run you command in c# and also you can get the result of the Console in your C#.
string WorkDir = #"C:\Users\rwong\Desktop\TestFiles";
Directory.SetCurrentDirectory(WorkDir);
String[] SubWorkDir = Directory.GetDirectories(WorkDir);
foreach (string subdir in SubWorkDir)
{
string[] filelist = Directory.GetFiles(subdir);
for(int f = 0; f < filelist.Length; f++)
{
if (filelist[f].ToLower().EndsWith(".pdf") || filelist[f].EndsWith(".PDF"))
{
PDFReader reader = new Pdfreader(filelist[f]);
bool PDFCheck = reader.IsOpenedWithFullPermissions;
reader.CLose()l
if(!PDFCheck)
{
string PNGPath = Path.ChangeExtension(filelistf], ".png");
string PDFfile = '"' + filelist[f] + '"';
string PNGfile = '"' + PNGPath + '"';
string arguments = string.Format("{0} {1}", PDFfile, PNGfile);
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.EnableRaisingEvents = true;
p.StartInfo.CreateNoWindow = true;
p.startInfo.FileName = "C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe";
p.startInfo.Arguments = arguments;
p.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
//You can receive the output provided by the Command prompt in Process_OutputDataReceived
p.Start();
}
}
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
string s = e.Data.ToString();
s = s.Replace("\0", string.Empty);
//Show s
Console.WriteLine(s);
}
}

Why command doesn't executes if contains Russian letters?

I tried to disconnect/connect my modem adapter, named as "конект", but it doesn't work, because adapter's name contains Russian letters. How to force it to work? Please help.
Connect("конект", "", "", true);
public static void Connect(string adapter, string login, string pass, bool discon)
{
string cmd = "";
if (discon)
{
cmd = "rasdial " + '"' + adapter + '"' + #" /disconnect";
}
else
{
cmd = "rasdial " + '"' + adapter + '"' + " " + login + " " + pass;
}
Cmd(cmd);
}
public static void Cmd(string URL)
{
ProcessStartInfo startInfo = new ProcessStartInfo("CMD.exe");
Process p = new Process();
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
p = Process.Start(startInfo);
p.StandardInput.WriteLine(URL);
p.StandardInput.WriteLine(#"EXIT");
p.WaitForExit();
p.Close();
}
[I know that need just rename adapter with English letters and code will work, but I want to know how to force it work with Russian letters]
p.StandardInput.WriteLine(URL);
ProcessStartInfo is missing a StandardInputEncoding property. That makes it likely that a "URL" string that contains Cyrillic characters is going to get mangled if this code runs on machine that doesn't have a cyrillic code page as the default system code page.
You really want to avoid using input redirection here, it just isn't necessary. Use the /c command option for cmd.exe so that you can pass the command line directly:
startInfo.Arguments = "/c " + URL;
p = Process.Start(startInfo);
Fwiw, not necessary to use cmd.exe either, just run rasdial.exe directly.

How to uninstall Software using c# by calling Software UninstallString Listed in Registry file of that Software But the Process Is Not Working

I am developing a software that will list all the software install
in Computer
now i want to Uninstall it using my Program In C# by
calling the Uninstall Key of that software in
Registry Key
My Program Is
Like That But the Process Is Not Working
var UninstallDir = "MsiExec.exe /I{F98C2FAC-6DFB-43AB-8B99-8F6907589021}";
string _path = "";
string _args = "";
Process _Process = new Process();
if (UninstallDir != null && UninstallDir != "")
{
if (UninstallDir.StartsWith("rundll32.exe"))
{
_args = ConstructPath(UninstallDir);
_Process.StartInfo.FileName = Environment.SystemDirectory.ToString() + "\\explorer.exe";
_Process.StartInfo.Arguments = Environment.SystemDirectory.ToString() + "\\" + UninstallDir;
_Process.Start();
}
else if (UninstallDir.StartsWith("MsiExec.exe"))
{
_args = ConstructPath(UninstallDir);
_Process.StartInfo.FileName = Environment.SystemDirectory.ToString() + "\\cmd.exe";
_Process.StartInfo.Arguments = Environment.SystemDirectory.ToString() + "\\" + UninstallDir;
_Process.Start();
}
else
{
//string Path = ConstructPath(UninstallDir);
_path = ConstructPath(UninstallDir);
if (_path.Length > 0)
{
_Process.StartInfo.FileName = _path;
_Process.StartInfo.UseShellExecute = false;
_Process.Start();
}
}
Try this approach:
Process p = new Process();
p.StartInfo.FileName = "msiexec.exe";
p.StartInfo.Arguments = "/x {F98C2FAC-6DFB-43AB-8B99-8F6907589021}/qn";
p.Start();
Refer to this link: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/msiexec.mspx?mfr=true
HTH.
The problem with your misexec.exe code is that running cmd.exe someprogram.exe doesn't start the program because cmd.exe doesn't execute arguments passed to it. But, you can tell it to by using the /C switch as seen here. In your case this should work:
_Process.StartInfo.FileName = Environment.SystemDirectory.ToString() + "\\cmd.exe";
_Process.StartInfo.Arguments = "/C " + Environment.SystemDirectory.ToString() + "\\" + UninstallDir;
Where all I did was add /C (with a space after) to the beginning of the arguments. I don't know how to get your rundll32.exe code to work, however.
Your solution looks good, but keep a space before \qn:
p.StartInfo.Arguments = "/x {F98C2FAC-6DFB-43AB-8B99-8F6907589021} /qn";
Otherwise it wont work in silent mode.

Problem with spaces in a filepath - commandline execution in C#

I am building a gui for a commandline program.
In txtBoxUrls[TextBox] file paths are entered line by line.
If the file path contains spaces the program is not working properly.
The program is given below.
string[] urls = txtBoxUrls.Text.ToString().Split(new char[] { '\n', '\r' });
string s1;
string text;
foreach (string s in urls)
{
if (s.Contains(" "))
{
s1 = #"""" + s + #"""";
text += s1 + " ";
}
else
{
text += s + " ";
}
}
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = #"wk.exe";
proc.StartInfo.Arguments = text + " " + txtFileName.Text;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
//Get program output
string strOutput = proc.StandardOutput.ReadToEnd();
//Wait for process to finish
proc.WaitForExit();
For example if the file path entered in txtBoxUrls is "C:\VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm", The program will not work. This file path with double quotes will work in the windows command line(I am not using the GUI) nicely.
What would be the solution.
proc.StartInfo.Arguments = text + " " + txtBoxUrls.Text + " " + txtFileName.Text;
In this line, text already contains the properly quoted version of your txtBoxUrls strings. Why do you add them again in unquoted form (+ txtBoxUrls.Text)? If I understood your code corrently, the following should work:
proc.StartInfo.Arguments = text + " " + txtFileName.Text;
In fact, since txtFileName.Text could probably contain spaces, you should quote it as well, just to be sure:
proc.StartInfo.Arguments = text + " \"" + txtFileName.Text + "\"";
(or, using your syntax:)
proc.StartInfo.Arguments = text + #" """ + txtFileName.Text + #"""";
Usually to get around spaces in filenames, you'll need to wrap your argument in double quotes. If you leave out the quotes the program will think it has two arguments. Something like this...
wk.exe "C:\VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm"
Also, this line appears to have too many quotes. Four, instead of three:
s1 = #"""" + s + #"""";
Take a look at the Path class - http://msdn.microsoft.com/en-us/library/system.io.path.aspx
Path.combine might be what you are looking for.

Categories