Process.Start not executing command - c#

I am using ImageMagick C# tool to convert PDF to JPG by calling the executable from C#. I believe I set up the command correctly but it does not execute; it just passes through Process.Start(startInfo) without executing it. I do see the command prompt popping up but nothing happens.
string PNGPath = Path.ChangeExtension(Loan_list[f], ".png");
string PDFfile = '"' + Loan_list[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 wasn't sure if it was because of the double quotes I added to each argument before hand but after commenting it out and running it again, it still skipped over. Any thoughts?
Edit: To add some clarity, I am expecting a JPG files from a PDF but I see no output file from this part of code. I ran the following in my command prompt to convert PDF to JPG
"C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe" "C:\Users\rwong\Desktop\RoundPoint\1000965275\1000965275_157_Credit File_10.PDF" "C:\Users\rwong\Desktop\RoundPoint\1000965275\1000965275_157_Credit File_10.png"
I explicitly called the convert.exe for clarity sake in my code. The command works fine in command prompt but when coping the structure over to C# it doesn't do anything. I see the code step into it but it continues without an error.
Edit2: Upon request below is the code and output for a Process Exit code
string PNGPath = Path.ChangeExtension(Loan_list[f], ".png");
string PDFfile = '"' + Loan_list[f] + '"';
string PNGfile = '"' + PNGPath + '"';
try
{
Process myprocess = null;
string[] arguments = { PDFfile, PNGfile };
myprocess=Process.Start(#"C:\ProgramFiles\ImageMagick6.9.2Q16\convert.exe", String.Join(" ", arguments));
Console.WriteLine("Process exit code: {0}", myprocess.ExitCode);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Process exit code: 1

Assuming that you are right and there was a problem (rather than the process just executed very quickly and exited), you can check the return code as follows:
if (Process.Start(startInfo) == null)
{
int lastError = Marshal.GetLastWin32Error();
}
You then go here to look up the error code:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx
Hopefully, that vendor actually sets an error code on failure (they may or may not).

Related

Powershell Timeout From C#

I want to set a timeout on powershell scripts I have running in c#.
My code to run my scripts is
private void RunPowerShell(string scriptText)
{
string tempFile = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "PinScript.ps1");
var file = new StreamWriter(tempFile);
file.AutoFlush = true;
file.WriteLine(scriptText);
file.Dispose();
string output, errors = string.Empty;
//this is basically a helper method that runs an exe via the command prompt in c#
//I want to keep this as is and either add an argument to powershell.exe or alter the
//.psi scripts themselves
_cmd.Run(#"powershell.exe",
#"-NoProfile -ExecutionPolicy Bypass " + #"& '" + tempFile + "'",
out output,
out errors);
Console.WriteLine("Powershell Output: " + output);
Console.WriteLine("Powershell Errors: " + errors);
File.Delete(tempFile);
}
I see there is code that works to time out a script here but I cannot understand how to ingrate that concept into what I have above.

text file not updating in the run problem c#

I have the following code:
strCmdText = "/C cppcheck.exe --enable=all " + StrFile1 + " 2> " + StrfolderOut + "\\fileOut.txt";
//Console.WriteLine(strCmdText);
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
but when I'm trying to read it afterwards is like the program executes it after finishing the execution
I ran 2 test:
First one I use as an input "file1.txt" (fileOut does not exist) the file is created by cmd redirecting the output using ">". When trying to read it it says "the file does not exist"
Secondly, I use "file2.txt" as an input (fileOut does existe and has the info of file2.txt) and it reads but the content of "file1.txt".
So I think that the cmd command runs after finishing the execution. I triple checked the paths so is not a problem since im reading the path using file folder gui.
I'm using this code to read
public List<Error> LeerArchivo()
{
List<Error> listaErrores = new List<Error>();
string #folderLocation = StrfolderOut + "\\fileOut.txt";
Console.WriteLine(#folderLocation);
//OpenFileDialog openFileDialog = new OpenFileDialog();
//openFileDialog.ShowDialog();
if (File.Exists(#folderLocation))
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(#folderLocation))
{
string line = "";
// Read and display lines from the file until the end of
// the file is reached.
Console.WriteLine("reading");
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
Console.WriteLine(line);
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
else
{
Console.WriteLine("no existe");
}
return listaErrores;
}
I manage it to work, I used:
Process process = new Process();
process.StartInfo.FileName = "CMD.exe";
{do cppcheck... etc}
process.Start();
process.WaitForExit();
It works now, I think it is since the main program waits for that process to finish. Maybe I can have a deeper explanation of what happening.

SCHTASKS Invalid Syntax in C# but working in CMD

I've got a command I'm trying to run through C# to get a list of tasks in CSV format from a bunch of computers.
To do this, I am using the SCHTASKS command with command redirection to a CSV. So I wrote this code in C# to do this for me:
string commandGetStatus = "schtasks";
string argumentsGetStatus = "/s:" + CompName +
" /fo:csv" +
" > \"" + #"\\BIG\OL\UNC\PATH\"+CompName+".csv" + "\"";
getLatestTaskStatus.StartInfo.FileName = commandGetStatus;
getLatestTaskStatus.StartInfo.Arguments = argumentsGetStatus;
getLatestTaskStatus.StartInfo.CreateNoWindow = true;
getLatestTaskStatus.StartInfo.RedirectStandardOutput = true;
getLatestTaskStatus.StartInfo.RedirectStandardInput = true;
getLatestTaskStatus.StartInfo.RedirectStandardError = true;
getLatestTaskStatus.StartInfo.UseShellExecute = false;
getLatestTaskStatus.Start();
It returns the output:
ERROR: Invalid syntax.
Type "SCHTASKS /?" for usage.
So I used StartInfo.FileName + " " + StartInfo.Arguments to print out the exact command that should be being executed. From there, I copy and pasted the command into CMD. Where it worked without a problem. This was the command + args:
schtasks /s:COMPUTERNAME /fo:csv > "\\BIG\OL\UNC\PATH\COMPUTERNAME.csv"
I'm not sure what the problem is at this point.
My Solution
Luaan was absolutely correct about the problem. The command prompt redirection operator,>, is not available without using Command Prompt. Fortunately, the solution was quote simple and easy to implement. I reduced the argument variable to:
"/s:" + CompName + " /fo:csv"
And with standard output being redirected, I simply used:
string output = process.StandardOuptut.ReadToEnd();
File.WriteAllText(#"\\UNC\File\Path\" + myfile + ".csv", output);
You explicitly disabled UseShellExecute - > is a shell operator, not something inherent to processes. It definitely isn't an argument. You need to read the output and write it out manually :)

Issue when passing multiple arguments to an external exe program using c#

I have an exe file in which I am trying to pass arguments through c#. the code is as follows
class Class1
{
static void Main()
{
string[] arg;
arg = new string[3];
Process p = new Process();
p.StartInfo.FileName = #"D:\xxx.exe";
for (int i = 0; i < 3; i++)
{
arg[i] = Console.ReadLine();
}
p.StartInfo.Arguments = arg[0] + " " + arg[1] + " " + arg[2];
p.Start();
}
}
I open up a console and then write the arguments there. As soon as I am finished typing 3 arguments, I make a string out of the 3 arguments and then call Process.Start() with the arguments in the p.StartInfo.Arguments string. The exe file loads but it does not generate any output. The strange thing is that if I open the exe file from my computer and then write
Arg1.txt Arg2.txt Arg3.txt
and press enter the exe file generates the output. However the same arguments in the same style are currently being passed through C# code and it is not generating any output. I donot understand what I am doing wrong. There are multiple questions on StackOverflow about this, I know that, however they all suggest the same procedure as what I have done here. I have also tried giving arguments as
p.StartInfo.Arguments = "\"arg[0]\"\"arg[1]\"\"arg[2]\"";
but this also has not worked.
Try this:
p.StartInfo.Arguments = "\"" + arg[0] + " " + arg[1] + " " + arg[2] + "\"";
p.Start();
It is recomended to use "" when you use several parameters between gaps.
EDIT: No "\" have to be included if you type it ok. It is the escape character. See picture below.

unzip file in C# via Winzip and its cmd extension

so I have a small chunk of code that detects files in a folder and systematically zips them after they become a certain age. I'm now working on a piece of code to unzip files of a certain date-range at user request for use in the software.
My issue is that the command-line string to zip files works great, but the unzip does not... below is the excerpt of code showing how I unzip, please let me know what I should do differently to ensure unzipping. thanks!
private void UnZipFile()
{
if (myRecord == null)
{
if (File.Exists(zipInfo.FullName))
{
Process LogUnzipper = new Process();
//32-bit system
if (File.Exists("c:\\Program Files\\WinZip\\WZZIP.exe"))
{
//WZZIP.exe being the WinZip executable
LogUnzipper.StartInfo.FileName = "c:\\Program Files\\WinZip\\WZZIP.exe";
}
//64-bit system
else if (File.Exists("c:\\Program Files (x86)\\WinZip\\WZZIP.exe"))
{
//WZZIP.exe being the WinZip executable
LogUnzipper.StartInfo.FileName = "c:\\Program Files (x86)\\WinZip\\WZZIP.exe";
}
//here is where I think I'm screwing up something..
string action = "-e " + "\"" + zipInfo.FullName + "\"" + " \"" + zipInfo.DirectoryName + "\"";
//happen in background
LogUnzipper.StartInfo.CreateNoWindow = true;
LogUnzipper.StartInfo.UseShellExecute = false;
LogUnzipper.StartInfo.Arguments = action;
LogUnzipper.Start();
while (!LogUnzipper.HasExited)
{
LogUnzipper.WaitForExit(500);// 1/2 sec
}
//adding break point at this line yields no unzipped Log file :(
}
...
my thoughts are that I'm somehow calling the cmd wrong in string action? even though if I test it in a windows command prompt that's correct formatting.
***it should be noted that ZipInfo.FullName is something along the ex: "C:\Users\16208\Software\Beta\logs\6_2013\Log_10AM_to_11AM.zip" as far as formmat, so I am giving an accurate path to the zipped Item.
You can use some free and open-source .Net library for zipping and unzipping (as SLaks suggested). For example DotNetZip.
using (ZipFile decompress = ZipFile.Read(ZipFilePath))
{
foreach (ZipEntry e in decompress)
{
e.Extract(TargetPath, ExtractExistingFileAction.OverwriteSilently);
}
}
As for your code, waiting half a second may not be enough for unzipping to complete. Also you can try running your unzip command in a command line and check the output.
If you have WinZip installed try this:
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", #"/c start winzip32 -e " + fileName + #" C:\SomeDirectory");
rocStartInfo.UseShellExecute = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
Where fileName is the full path to your *.rar file.

Categories