I am working on a program that needs to extract a WinRar SFX automatically. Is there anyway I can programmatically click a install button once the exe is started with a Process? Here is the code that I have so far.
public bool Extract()
{
try
{
Process process = new Process();
process.StartInfo.WorkingDirectory = FilePath;
process.StartInfo.FileName = FilePath + fileName;
process.Start();
process.WaitForExit();
}
catch (Exception)
{
return false;
}
return true;
}
You could make the sfx silent with winrar.
Here is a link
Related
So I'm trying to run an .exe on my windows server that requires a user with specific access rights to run it. Luckily I have those rights on the server and can run the executable just fine manually.
However when I want to run it from my code, which is a .net core console API application I encounter a problem saying: 'The handle is invalid'.
Here is the method where Im trying to achieve this:
public void UpdateDataSets()
{
try
{
Process processStart = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(#"PathToExecutable.exe");
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.Arguments = $#"MyArguments";
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.UserName = "MyUserName";
startInfo.Domain = "MyDomain";
startInfo.Password = new NetworkCredential("", "MyUserPassword").SecurePassword;
processStart.StartInfo = startInfo;
string textToRead;
using(Process process = Process.Start(startInfo))
{
textToRead = process.StandardOutput.ReadToEnd();
process.WaitForExit(20000); //time limit because maybe infinite, I dont know?
}
File.WriteAllText(#"StandardOutput.txt", textToRead);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
}
}
I first tried with startInfo.Verb = "runas" and with startInfo.LoadUserProfile = true before hard-coding my active directory credentials, but I just got different errors there.
What am I doing wrong here?
I am working with Visual Studio 2015 and .NET framework 4.7.2. I have set up a simple test program that executes an external program in C#. The program is a Python script that simply prints some string to stdout every 0.5 seconds. I want to read the stdout of this sub process in my C# application.
The program basically works, but I get the output of the Python script only shortly before the sub process exits. What do I need to change in order to get a more responsive behavior, i.e. getting the output every 0.5 second as soon as the Python script writes it to stdout?
Here's my C# code:
public class Program {
private Process process;
public static void Main(string[] args) {
new Program().init();
}
private void init() {
startPythonProcess();
process.WaitForExit();
Console.ReadLine();
}
private void startPythonProcess() {
if(process==null) {
try {
Console.WriteLine("Starting Python process ...");
string filepath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Substring(6);
process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = filepath;
startInfo.FileName = "python.exe";
//startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.RedirectStandardInput = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.Arguments = string.Format("{0}", Path.Combine(filepath, "test.py"));
process.StartInfo = startInfo;
process.OutputDataReceived += OutputDataReceivedEventHandler;
process.ErrorDataReceived += ErrorDataReceivedEventHandler;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
} catch(Exception ex) {
Console.WriteLine("Could not start Python process: " + ex.Message);
}
}
}
public void OutputDataReceivedEventHandler(object sender, DataReceivedEventArgs args) {
Console.WriteLine("[PYTHON] INFO: {0}", args.Data);
}
public void ErrorDataReceivedEventHandler(object sender, DataReceivedEventArgs args) {
Console.WriteLine("[PYTHON] ERROR: {0}", args.Data);
}
}
Here's my Python script:
import time
import sys
import logging
logging.basicConfig(level=logging.ERROR)
if __name__ == '__main__':
count = 0
while True:
print('PYTHON: {}'.format(count))
time.sleep(0.5)
count+=1
if count>=25:
break
UPDATE: I uploaded the mini project here.
The print function takes a flush argument which controls whether buffered output is flushed.
The default value of flush is False, meaning flushing is controlled by whatever file print is writing to (for example, sys.stdout).
Set flush to True to force immediate printing.
print('PYTHON: {}'.format(count), flush=True)
I am trying to run a batch file that runs another batch file from my windows application.
when i click the button, everything is frozen and i do not know why.
The nested batch file was created to build html files from RST files
I have a feeling that I am in a dead lock situation.
Thank you so much guys for your help.
I have attached a screen shot of my form and included my code as well.
private void buttonMakeHtml_Click(object sender, EventArgs e)
{
ProcessStartInfo processInfo =
new ProcessStartInfo("cmd.exe", "/c" + "\"C:\\ReadTheDocs\\makeHtml.bat\"");
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
var process = Process.Start(processInfo);
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
textBoxOutPut.Text = output;
textBoxError.Text = error;
}
Make html Screen
I have code that I took from How can I send a file document to the printer and have it print?. When I was running this on my machine, it worked flawlessly. Once I put it on a VM for testing, it is no longer printing. I discovered this is probably due to the application not opening Adobe. I have given access to the folder where the PDFs reside in, and changed the security settings in Adobe.
My code:
try
{
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.FileName = #"properFilePath.pdf";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Normal; // so I know Adobe is opening
TimeSpan tp = new TimeSpan(0, 0, 10); // I thought this did something different than what it really does
Process p = new Process();
p.StartInfo = info;
p.Start();
p.WaitForInputIdle();
System.Threading.Thread.Sleep(tp);
if (false == p.CloseMainWindow())
{
p.Kill();
}
Message m = new Message() { Msg = "Worked, yo", MsgType = Message.MessageType.Success };
Logger.Log(m);
return true;
}
catch (Exception ex)
{
//I log this I swear
return false;
}
I'm looking to be pointed in the right direction for solutions/help/answers.
Thanks
I have a batch file which runs perfectly fine if I give this command in the command prompt.
C:\app> C:\app\Process.bat C:\app\files\uploads c:\app\files file2 <- WORKS
So there are just 3 input parameters.
C:\app\files\uploads : the folder location of input files
c:\app\files : the output folder
file2 : output file name
If I run the batch file from C:\app folder I see the output file
I want to automate the process from a console app which will be scheduled job
But running in visual studio debug mode or clicking the exe file does nothing.
I don't get any kind of exception either.
What can be wrong - permission or other thing I am doing wrong?
This is the C# code
static void Main(string[] args)
{
RunBatchFile(#"C:\app\Process.bat", #"C:\app\files\uploads c:\app\files 123456");
}
public static string RunBatchFile(string fullPathToBatch, string args)
{
using (var proc = new Process
{
StartInfo =
{
Arguments = args,
FileName = fullPathToBatch,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = false,
RedirectStandardError = false
}
})
{
try
{
proc.Start();
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == 2)
{
return "File not found exception";
}
else if (e.NativeErrorCode == 5)
{
return "Access Denied Exception";
}
}
}
return "OK";
}
2 Issues here:
First problem is you need to execute cmd.exe not the batch file.
Second, you are executing it but you need to wait for the process to complete. Your app is the parent process and because you're not waiting the child process doesn't complete.
You need to issue a WaitForExit():
var process = Process.Start(...);
process.WaitForExit();
Here is what you want to do:
static void ExecuteCommand(string command)
{
int exitCode;
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
process = Process.Start(processInfo);
process.WaitForExit();
exitCode = process.ExitCode;
process.Close();
}
To run your batch file do this from the main():
ExecuteCommand("C:\app\Process.bat C:\app\files\uploads c:\app\files file2");