Running process openfiles output result to file - c#

I am trying to output the result of the openfiles process to a file but I am not getting any result can someone explain why? I have tried it 2 different ways. If I use the command prompt and run the same process it does display a result to my file.
Update: I added a third method with the change redirectstandardoutput = true
I tried this and now I get a file but with no results
Update:
I found the problem it is with the build option being set to x86 when doing this on a 64bit system I think it is running the 32bit version of openfiles. I tested by running my app and using the RedirectStandardError stream which I should have been doing in the first place :) and this is what it said "ERROR: The target system must be running a 32 bit OS."
//First Method
using (Process proc = new Process())
{
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "openfiles";
proc.StartInfo.Arguments = "/query /FO CSV /v > " + "\"" + Application.StartupPath + #"\OpenFiles.log" + "\"";
proc.Start();
}
//Second method
using (Process proc = new Process())
{
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "cmd";
proc.StartInfo.Arguments = "/C openfiles /query /FO CSV /v > " + "\"" + Application.StartupPath + #"\OpenFiles.log" + "\"";
proc.Start();
}
//Third method
using (Process proc = new Process())
{
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.FileName = "openfiles";
proc.StartInfo.Arguments = "/query /FO CSV /v";
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
if (output != null)
File.WriteAllText(Path.Combine(Application.StartupPath, "OpenFiles.log"), output);
}

The redirect will not work like that as > filename is not seen as an 'argument'.
Typically, you will capture the output in your application and write it to a file yourself:
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
File.WriteAllText(Path.Combine(Application.StartupPath, "OpenFiles.log"), output);

Related

How to execute the set path=c:\Project Work\jdk1.8.0_66-x64\jre\bin;%PATH% command from C#

I am trying to run an executable JAR file and it has to run using jre version 1.8.
when I run this command manually from CMD I am getting the jre version as 1.8.
set path=c:\Project Work\jdk1.8.0_66-x64\jre\bin;%PATH%
How can I run this command from C#. I tried the following code but not able to execute the command from c#.
try
{
string command = "set path=c:\\Project Work\\jdk1.8.0_66-x64\\jre\bin;%PATH%";
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);
Console.WriteLine(procStartInfo.WorkingDirectory);
Console.ReadLine();
}
catch (Exception objException)
{
// Log the exception
}
Please provide your inputs to execute the command.
I am able to execute the command by following the below steps
1. I have written a batch file with the command
set path=c:\Project Work\jdk1.8.0_66-x64\jre\bin;%PATH%
2. I have named the batch file and executed the batch file from C# program in the following way.
string abc = "abc";
string def = "123";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "C:\\Users\\90008121\\Desktop\\ClassPathbatch.bat";
proc.StartInfo.Arguments = String.Format("{0} {1}", abc, def);
proc.StartInfo.RedirectStandardError = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
Console.ReadLine();
3. Finally the requirement is met.

COPY command can't find the path specified when run in C#

When I run he following command from the command line it works fine.
COPY "C:\Windows\System32\winevt\Logs\Application.evtx" "C:\ProgramData\MyCompany\Support\Logs\Application.evtx"
But I want to run it using the following in C#
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + CurrentCommand);
StreamReader.procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
while (!proc.StandardError.EndOfStream)
{
sError = proc.StandardError.ReadLine();
//System.Windows.Forms.MessageBox.Show("ERROR: " + sError);
}
proc.WaitForExit();
// Get the output into a string
sResult = proc.StandardOutput.ReadToEnd();
sResult returns the following error:
The system cannot find the path specified
Why is this?
I guess you need to "escape" the command parameters for the cmd /c argument like
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", string.Format("/c \"{0}\"", CurrentCommand));

how to start process with hidden window

I have this code:
string d = "-f image2 -framerate 9 -i E:\\REC\\Temp\\%06d.jpeg -r 30 E:\\REC\\Video\\" + label1.Text + ".avi";
//string d = "-f dshow -i video=\"screen-capture-recorder\" E:\\REC\\" + label1.Text + ".flv";
Process proc = new Process();
proc.StartInfo.FileName = "E:\\ffmpeg\\bin\\ffmpeg.exe";
proc.StartInfo.Arguments = d;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
if (!proc.Start())
{
Console.WriteLine("Error starting");
return;
}
proc.WaitForExit();
When it runs the ffmpeg.exe is there like this:
My question is how to hide this window?
You need the following combination of settings:
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
And that's it.
The reason being that the key setting is CreateNoWindow which has to be true. But CreateNoWindow only has any effect when UseShellExecute is false. That's because CreateNoWindow maps to the CREATE_NO_WINDOW process creation flag passed to CreateProcess. And CreateProcess is only called when UseShellExecute is false.
More information can be found from the documentation:
Property Value
true if the process should be started without creating a new window to contain it; otherwise, false. The default is false.
Remarks
If the UseShellExecute property is true or the UserName and Password
properties are not null, the CreateNoWindow property value is ignored
and a new window is created.
This on keeps the all processes in same console window. no allow to open an new one`
Process process = new Process();
// Stop the process from opening a new window
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
// Setup executable and parameters
process.StartInfo.FileName = #"E:\\ffmpeg\\bin\\ffmpeg.exe"
//Optional
string d = "-f image2 -framerate 9 -i E:\\REC\\Temp\\%06d.jpeg -r 30 E:\\REC\\Video\\" + label1.Text + ".avi";
process.StartInfo.Arguments = d;
// Go
process.Start();

Running an exe in C# with commandline parameters, suppressing the dos window

I am using lame for transcoding for one of my project. The issue is that when I call lame from C#, a DOS window pops out. Is there any way I can suppress this?
Here is my code so far:
Process converter =
Process.Start(lameExePath, "-V2 \"" + waveFile + "\" \"" + mp3File + "\"");
converter.WaitForExit();
Did you try something like:
using( var process = new Process() )
{
process.StartInfo.FileName = "...";
process.StartInfo.WorkingDirectory = "...";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.Start();
}
Assuming you are calling it via Process.Start, you can use the overload that takes ProcessStartInfo that has its CreateNoWindow property set to true and its UseShellExecute set to false.
The ProcessStartInfo object can also be accessed via the Process.StartInfo property and can be set there directly before starting the process (easier if you have a small number of properties to setup).
Process bhd = new Process();
bhd.StartInfo.FileName = "NSOMod.exe";
bhd.StartInfo.Arguments = "/mod NSOmod /d";
bhd.StartInfo.CreateNoWindow = true;
bhd.StartInfo.UseShellExecute = false;
Is another way.
This is my code that does a similar thing, (and also reads the output and return code)
process.StartInfo.FileName = toolFilePath;
process.StartInfo.Arguments = parameters;
process.StartInfo.UseShellExecute = false; // needs to be false in order to redirect output
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true; // redirect all 3, as it should be all 3 or none
process.StartInfo.WorkingDirectory = Path.GetDirectoryName(toolFilePath);
process.StartInfo.Domain = domain;
process.StartInfo.UserName = userName;
process.StartInfo.Password = decryptedPassword;
process.Start();
output = process.StandardOutput.ReadToEnd(); // read the output here...
process.WaitForExit(); // ...then wait for exit, as after exit, it can't read the output
returnCode = process.ExitCode;
process.Close(); // once we have read the exit code, can close the process

How to hide cmd window while running a batch file?

How to hide cmd window while running a batch file?
I use the following code to run batch file
process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();
If proc.StartInfo.UseShellExecute is false, then you are launching the process and can use:
proc.StartInfo.CreateNoWindow = true;
If proc.StartInfo.UseShellExecute is true, then the OS is launching the process and you have to provide a "hint" to the process via:
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
However the called application may ignore this latter request.
If using UseShellExecute = false, you might want to consider redirecting standard output/error, to capture any logging produced:
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
proc.StartInfo.RedirectStandardError = true;
proc.ErrorDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
And have a function like
private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data)) // use the output outLine.Data somehow;
}
There's a good page covering CreateNoWindow this on an MSDN blog.
There is also a bug in Windows which may throw a dialog and defeat CreateNoWindow if you are passing a username/password. For details
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476
http://support.microsoft.com/?kbid=818858
According to the Process properties, you do have a:
Property: CreateNoWindow
Notes: Allows you to run a command line program silently.
It does not flash a console window.
and:
Property: WindowStyle
Notes: Use this to set windows as hidden.
The author has used ProcessWindowStyle.Hidden often.
As an example!
static void LaunchCommandLineApp()
{
// For the example
const string ex1 = "C:\\";
const string ex2 = "C:\\Dir";
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "dcm2jpg.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;
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
{
// Log error.
}
}
Use:
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
This is what worked for me,
When you redirect all of the input and output, and set the window hidden it should work
Process p = new Process();
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
try with this and this where the c# code is embedded into the batch files:
#echo off
echo self minimizing
call getCmdPid.bat
call windowMode.bat -pid %errorlevel% -mode minimized
echo --other commands--
pause
Though it might be not so easy to unhide the window.

Categories