StandardOutput.ReadToEnd() always NULL - c#

I have a problem with this function. It is supposed to output an install command to a textbox but install.StandardOutput.ReadToEnd() is always null.
I get the error: Expression cannot be evaluated because there is a native frame at the top of the call stack
Can you help me out with this?
Process install = new Process();
install.StartInfo.FileName = "cmd.exe";
install.StartInfo.UseShellExecute = false;
install.StartInfo.Arguments = "/all";
install.StartInfo.CreateNoWindow = true;
install.StartInfo.RedirectStandardInput = true;
install.StartInfo.RedirectStandardOutput = true;
install.Start();
if (CB_MultiADB.Checked == true)
{
install.StandardInput.WriteLine("FOR /F \"skip=1\" %%x IN ('adb devices') DO start cmd.exe #cmd /k" + InstallOption + InstallPfad + "\"");
}
else
{
install.StandardInput.WriteLine("adb install" + InstallOption + InstallPfad + "\"");
InstallAusgabe = install.StandardOutput.ReadToEnd();
string Index = "adb install";
int Indexnr = InstallAusgabe.IndexOf(Index);
string SubInstall = InstallAusgabe.Substring(Indexnr, 100);
TB_Ausgabe.Text = SubInstall;
}

Related

Vbs script working fine with CMD but not in Code

When I execute the script via code it's going in an infinite loop. But same script working in CMD
tried with CMD and It's working but not working in code. Take any VB Script as a sample and validate.
private string excecuteScript(string retValue)
{
try
{
string filetoexecute = Path.Combine(Application.StartupPath, Path.GetExtension(ScriptName).EndsWith(".vbs",StringComparison.InvariantCultureIgnoreCase) ? "AA_MyVB.vbs" : "AA_MyJS.js");
filetoexecute = string.Format("\"" + filetoexecute + "\"");
string arguments = " " + filetoexecute + " " + ScriptInputPara + " \"" + ScriptName + "\" ";
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = Path.Combine(Environment.SystemDirectory, "WScript.exe"),
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var myProcess = CommonMethods.InvokeProcess(startInfo);
StreamReader errorStream = myProcess.StandardError;
StreamReader outputStream = myProcess.StandardOutput;
string theOutput = string.Empty;
bool stopWhile = false;
while (!stopWhile)
{
stopWhile = myProcess.HasExited;
if (CmdTask.IsTaskTimedout)
{
stopWhile = true;
myProcess.Kill();
}
}
theOutput += outputStream.ReadLine();
TheError += errorStream.ReadToEnd();
if (myProcess.ExitCode != 0)
{
TheError = "Error occurred while executing script file";
}
if (IsScriptTask && !string.IsNullOrEmpty(theOutput) && !string.IsNullOrEmpty(ScriptOutputPara))
CmdTask.SetVariableValue(ScriptOutputPara, theOutput);
}
catch (Exception ex)
{
retValue = (ex.Message);
}
return retValue;
}
Actual: myProcess.HasExited returns false
Expected: myProcess.HasExited returns true
if I execute theOutput += outputStream.ReadLine(); before while loop then myProcess.HasExited returns true...

Ghost script command dosent wait for WaitForExit()

Hi guys im trying to execute gs command by creating a process and i want it to wait until the process is completed. I used waitforexit() but its surpassing waitforexit().
public async void pdf2Png(string name, string pdf, int lastPage)
{
Stopwatch stopwatch = Stopwatch.StartNew();
Response.Write((stopwatch.ElapsedMilliseconds / 1000) + " pdf 2 png" + "<br>");
Process obj_process = null;
ProcessStartInfo obj_startinfo = null;
StreamWriter obj_writer = null;
string sOutputFile = Path.Combine(Path.GetDirectoryName(pdf), name + "%d.png"); ;
string inputFilePath = pdf;
int lP = lastPage;
Response.Write(sOutputFile + " : " + inputFilePath + "<br>");
string str_command = string.Format("gswin64 -dSAFER -dBATCH -dNOPAUSE -dFirstPage=1 -dLastPage=\"{0}\" -sDEVICE=png16m -r600 -sOutputFile=\"{1}\" \"{2}\"",
lP, sOutputFile, inputFilePath);
obj_startinfo = new ProcessStartInfo("cmd.exe");
obj_startinfo.UseShellExecute = false;
obj_startinfo.RedirectStandardInput = true;
obj_startinfo.RedirectStandardError = true;
obj_startinfo.RedirectStandardOutput = true;
obj_startinfo.CreateNoWindow = true;
obj_startinfo.ErrorDialog = false;
obj_startinfo.WindowStyle = ProcessWindowStyle.Hidden;
obj_process = Process.Start(obj_startinfo);
obj_writer = obj_process.StandardInput;
obj_writer.WriteLine(str_command);
obj_writer.Flush();
obj_writer.Close();
obj_writer.Dispose();
obj_writer = null;
obj_process.WaitForExit();
System.IO.File.WriteAllText(#"D:\shits not working.txt", str_command);
stopwatch.Stop();
Response.Write((stopwatch.ElapsedMilliseconds / 1000) + " pdf 2 png" + "<br>");
}
the line below "Waitforexit()" gets executed even before the png gets created and exits the process. what can i do?

when i use the gsutil in c# (diagnostics.process, cmd), it's does not end

I want to automate using gsutil in c #.
I use the "gsutil cp" command . If the file is small , the copied successfully . However, the file size is more than 10MB, the command is not end . I 've waited a long time , the command does not end .
This is my code.
String currentUser = Environment.UserName;
if (File.Exists(#"C:\Users\" + currentUser + #"\" + botoFileName) == false)
{
log.Error("can't find the confileFileName (" + botoFileName + ")");
return false;
}
log.Info("==========================================================");
log.Info("fileKey = " + fileKey);
string resultPro = null;
string resultError = null;
System.Diagnostics.ProcessStartInfo proInfo = new System.Diagnostics.ProcessStartInfo();
System.Diagnostics.Process pro = new System.Diagnostics.Process();
proInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
proInfo.CreateNoWindow = true;
proInfo.UseShellExecute = false;
proInfo.RedirectStandardOutput = true;
proInfo.RedirectStandardInput = true;
proInfo.RedirectStandardError = true;
pro.StartInfo = proInfo;
pro.Start();
pro.StandardInput.Write("c:" + Environment.NewLine);
pro.StandardInput.Write(#"set BOTO_PATH=C:\Users\" + currentUser + #"\" + botoFileName + Environment.NewLine);
if (usingCloudSdk.Equals("true"))
{
//when using google sdk and python
pro.StandardInput.Write(#"gsutil cp " + fileKey + " " + gcsPath + Environment.NewLine);
}
else
{
//when using only gsutil and python
pro.StandardInput.Write(#"cd C:\gsutil\gsutil" + Environment.NewLine);
pro.StandardInput.Write(#"python gsutil -m cp " + fileKey + " " + gcsPath + Environment.NewLine);
}
pro.StandardInput.Close();
resultPro = pro.StandardOutput.ReadToEnd();
resultError = pro.StandardError.ReadToEnd();
pro.WaitForExit();
pro.Close();
log.Info(resultPro);
log.Info(resultError);
log.Info("==========================================================");
if (resultError.IndexOf("Exception") != -1 || resultError.IndexOf("Fail") != -1)
{
return false;
}
return true;
please help me.

How to create a RAM Disk with imdisk and C#?

I'm trying to create a RAM Directory via imdisk in C#. Since the cmd command is something like: imdisk -a -s 512M -m X: -p "/fs:ntfs /q /y"
I looked up how to process cmd commands with C# and found several hints regarding ProcessStartInfo(). This class works almost the way I intend it to, but since imdisk needs administrator priviliges I'm kinda stuck. Even though the code block is executed without exceptions, I don't see any new devices within the Windows Explorer.
try
{
string initializeDisk = "imdisk -a ";
string imdiskSize = "-s 1024M ";
string mountPoint = "-m "+ MountPoint + " ";
string formatHdd = "-p '/fs:ntfs /q /y' ";
SecureString password = new SecureString();
password.AppendChar('0');
password.AppendChar('8');
password.AppendChar('1');
password.AppendChar('5');
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.FileName = "cmd";
procStartInfo.Verb = "runas";
procStartInfo.UserName = "Admin";
procStartInfo.Password = password;
procStartInfo.Arguments = initializeDisk + imdiskSize + mountPoint + formatHdd;
Process.Start(procStartInfo);
catch (Exception objException)
{
Console.WriteLine(objException);
}
I hope someone can give me a little hint, right now I'm out of ideas.
Well I solved my problem in a different way. Somehow it seems that imdisk didn't format the new RamDisk the way it should and therefor no disk were created. As soon as I deleted the formatting option the disk is created and needs to be formatted. Therefore I started another process and used the cmd command "format Drive:"
For anyone who is interested, my solution is as follows:
class RamDisk
{
public const string MountPoint = "X:";
public void createRamDisk()
{
try
{
string initializeDisk = "imdisk -a ";
string imdiskSize = "-s 1024M ";
string mountPoint = "-m "+ MountPoint + " ";
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
procStartInfo.FileName = "cmd";
procStartInfo.Arguments = "/C " + initializeDisk + imdiskSize + mountPoint;
Process.Start(procStartInfo);
formatRAMDisk();
}
catch (Exception objException)
{
Console.WriteLine("There was an Error, while trying to create a ramdisk! Do you have imdisk installed?");
Console.WriteLine(objException);
}
}
/**
* since the format option with imdisk doesn't seem to work
* use the fomat X: command via cmd
*
* as I would say in german:
* "Von hinten durch die Brust ins Auge"
* **/
private void formatRAMDisk(){
string cmdFormatHDD = "format " + MountPoint + "/Q /FS:NTFS";
SecureString password = new SecureString();
password.AppendChar('0');
password.AppendChar('8');
password.AppendChar('1');
password.AppendChar('5');
ProcessStartInfo formatRAMDiskProcess = new ProcessStartInfo();
formatRAMDiskProcess.UseShellExecute = false;
formatRAMDiskProcess.CreateNoWindow = true;
formatRAMDiskProcess.RedirectStandardInput = true;
formatRAMDiskProcess.FileName = "cmd";
formatRAMDiskProcess.Verb = "runas";
formatRAMDiskProcess.UserName = "Administrator";
formatRAMDiskProcess.Password = password;
formatRAMDiskProcess.Arguments = "/C " + cmdFormatHDD;
Process process = Process.Start(formatRAMDiskProcess);
sendCMDInput(process);
}
private void sendCMDInput(Process process)
{
StreamWriter inputWriter = process.StandardInput;
inputWriter.WriteLine("J");
inputWriter.Flush();
inputWriter.WriteLine("RAMDisk for valueable data");
inputWriter.Flush();
}
public string getMountPoint()
{
return MountPoint;
}
}
Doesn't cmd.exe need to have the /C command line option passed through to run a command passed through as an argument? May well be that cmd.exe is just ignoring what you're passing through in procStartInfo.Arguments because you haven't prepended "/C " onto the front of the Arguments.

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.

Categories