Start hidden process with different credentials in c# - c#

I am starting a process with different user credential. I want that this process start as hidden. I am using fallowing code.But it doesn't work. The process starts as visible.
private void f(){
try {
System.Security.SecureString ssPwd = new System.Security.SecureString();
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "app.exe";
process.StartInfo.Arguments = "Params";
process.StartInfo.LoadUserProfile = true;
process.StartInfo.Domain = domain;
process.StartInfo.UserName = username;
for (int x = 0; x < password.Length; x++) {
ssPwd.AppendChar(password[x]);
}
process.StartInfo.Password = ssPwd;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
process.WaitForExit();
} catch (Exception ex) {
Console.WriteLine("Exception occurred. " + ex.Message);
}
}

Related

print pdf with selected printer from dropdown

Hi all i am trying to print a pdf file. For this i have created a windows form application. My application print the pdf if i use the default printer of the system. But problem is that when i try to print the PDF file with selected printer from dropdown my code does not works.
private bool SendToPrinter(string filePath, string filename)
{
bool Status = false;
string PrinterName;
string PaperName;
PrinterName = "";
try
{
PrinterName = Convert.ToString(cmbPrinterList.SelectedItem);
// Set the printer.
AddPrinterConnection(PrinterName);
SetDefaultPrinter(PrinterName);
//Print the file with number of copies sent.
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.Arguments = "\"" + PrinterName + "\"";
info.FileName = #filePath + #"\" + filename;
info.CreateNoWindow = false;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.UseShellExecute = true;
Process p = new Process();
p.StartInfo = info;
p.Start();
p.WaitForInputIdle();
System.Threading.Thread.Sleep(2);
if (false == p.CloseMainWindow())
p.Kill();
Status = true;
}
catch (Exception ex)
{
}
return Status;
}
//Set the added printer as default printer.
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string Name);
//Add the printer connection for specified pName.
[DllImport("winspool.drv")]
public static extern bool AddPrinterConnection(string pName);
public bool viewTabOrder = true;
Try the below code
This is working with different printers for me. Hope it will help you too :)
public void SendToPrinter(string filePath, string Printer)
{
try
{
Process proc = new Process();
proc.Refresh();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.Verb = "printto";
proc.StartInfo.FileName = ConfigurationManager.AppSettings["ReaderPath"].ToString();
proc.StartInfo.Arguments = String.Format("/t \"{0}\" \"{1}\"", filePath, Printer);
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
if (proc.HasExited == false)
{
proc.WaitForExit(20000);
}
proc.EnableRaisingEvents = true;
proc.Close();
}
catch (Exception e)
{
}
}
Code to bind the Printers into dropdownlist.
cmbPrinter.Items.Insert(0, "--Select Printer--");
for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
{
var pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
cmbPrinter.Items.Insert(i + 1, pkInstalledPrinters);
}
And Pass the parameter as below
SendToPrinter(FilePath,cmbPrinter.SelectedItem.ToString());

How to read process Output Message from process within the process?

I am running an exe through commandline and getting following output.
C:\Users\sysadmin>C:\Users\sysadmin\Desktop\New_folder\Setup\PatchInstaller.exe
--mode=silent
C:\Users\sysadmin Begin Setup UI mode: Silent Error :
Another instance running, Only a single instance can be run at a time.
Exit Code: 11
i am running this through System.daignostics.process.
My issue is PatchInstaller.exe calling another process and the output of that nested process is what is visible with cmd. but the same result and exit code i am not able to get through Process object of PatchInstaller.exe.
Is there any way of getting output of process running within process?
Following is the code i have tired...
string command = #"C:\Users\sysadmin\Desktop\Setup\PatchInstaller.exe";
string result = string.Empty;
System.Diagnostics.ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command + " --mode=silent);
System.Diagnostics.Process proc = new Process();
procStartInfo.ErrorDialog = false;
procStartInfo.UseShellExecute = false;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
if (!string.IsNullOrEmpty(domain) && !string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pwd))
{
procStartInfo.Domain = domain;
procStartInfo.UserName = user;
System.Security.SecureString ss = new System.Security.SecureString();
foreach (char c in pwd) { ss.AppendChar(c); }
procStartInfo.Password = ss;
}
proc = System.Diagnostics.Process.Start(procStartInfo);
proc.ErrorDataReceived += delegate(object sender, System.Diagnostics.DataReceivedEventArgs errorLine)
{
if (errorLine.Data != null) result += "error:" + errorLine.Data +;
};
proc.OutputDataReceived += delegate(object sender, System.Diagnostics.DataReceivedEventArgs outputLine)
{
if (outputLine.Data != null) result += outputLine.Data +;
};
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
Process[] pname = Process.GetProcessesByName("PatchInstaller");
Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}
proc.WaitForExit();
I don't know much about ProcessStartInfo but I have used Process before and the way to get the information out of the standard output is shown as below, I assume it should be a similar way just by accessing the StandardOutput
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine(command);
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
var output = cmd.StandardOutput.ReadToEnd();
cmd.WaitForExit();
This code worked for me:
const int MAX_EXIT_WAIT_TIME = 3000;
// Fill needed data
string username = "";
string password = "";
string domain = "";
string appName = "";
var dir = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
var appFullPath = Path.Combine(dir, appName);
ProcessStartInfo psi = new ProcessStartInfo(appFullPath);
psi.UserName = username;
var securePass = new System.Security.SecureString();
foreach (var c in password)
securePass.AppendChar(c);
psi.Password = securePass;
psi.Domain = domain;
psi.LoadUserProfile = false;
psi.WorkingDirectory = dir;
psi.Arguments = "";
psi.RedirectStandardOutput = true;
// Create Process object, but not start it!
var proc = new Process();
proc.StartInfo = psi;
StringCollection values = new StringCollection();
DataReceivedEventHandler outputDataReceived = (o, e) =>
{
lock (values)
values.Add(e.Data);
};
try
{
proc.OutputDataReceived += outputDataReceived;
// Only here we start process
if (!proc.Start())
throw new InvalidOperationException("Couldn't start app");
proc.BeginOutputReadLine();
proc.WaitForExit(MAX_EXIT_WAIT_TIME);
}
finally { proc.OutputDataReceived -= outputDataReceived; }
Console.WriteLine("Read {0} ", values.Count);
foreach (var item in values)
Console.WriteLine(" {0}", item);

Launching exe using Process hangs on user input in c#

I am launching an exe using below code.I am able to run exe successfully but it haults for user input which asks user to enter a character'y' or 'n'(i.e. yes/No).What I want is that while running exe (silent installation i.e. no cmd window is available or no user interaction) i should be able to pass 'y' character as user input.
Below is my code
public bool launchExe(exeFilepath)
{
bool status = true;
try
{
using (var myProcess = new Process())
{
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = true;
myProcess.EnableRaisingEvents = true;
myProcess.StartInfo.WorkingDirectory = exeFilepath;
myProcess.StartInfo.FileName = "Launcher.exe";
myProcess.Start();
myProcess.WaitForExit();
if (myProcess.ExitCode == 0)
status = true;
else
status = false;
}
}
catch (Exception ex)
{
Logger.Information(ex.Message);
status = false;
}
return status;
}
Use ProcessStartInfo.RedirectStandardInput to write to your launched Process:
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.EnableRaisingEvents = true;
myProcess.StartInfo.WorkingDirectory = exeFilepath;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.Start();
Thread.Sleep(1000); // wait 1 second
StreamWriter myStreamWriter = myProcess.StandardInput;
myStreamWriter.WriteLine("y");

Running hg command in c#

I have create a C# application for make easy of committing changes to mercurial repository. i have use following code to run hg commands in c# process
static void ExecuteCMDCommand(string path, string command)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
//startInfo.CreateNoWindow = false;
startInfo.WorkingDirectory = path;
startInfo.UseShellExecute = false;
startInfo.FileName = "hg.exe";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
//startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = command;
Process myProcess = new Process();
try
{
myProcess.StartInfo = startInfo;
var sbOut = new StringBuilder();
var sbErr = new StringBuilder();
var sw = new Stopwatch();
sw.Start();
myProcess.Start();
TimeSpan firstRead = TimeSpan.Zero;
myProcess.OutputDataReceived += (s, e) =>
{
if (firstRead == TimeSpan.Zero)
{
firstRead = sw.Elapsed;
}
sbOut.Append(e.Data);
};
Console.WriteLine("**************" + sbOut.ToString());
myProcess.ErrorDataReceived += (s, e) => sbErr.Append(e.Data);
myProcess.BeginOutputReadLine();
myProcess.BeginErrorReadLine();
var eventsStarted = sw.Elapsed;
myProcess.WaitForExit();
var processExited = sw.Elapsed;
sw.Reset();
// string strOutput = myProcess.StandardOutput.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
}
finally {
myProcess.Close();
myProcess.Dispose();
}
}
this works for hg status/hg branches but when i execute hg pull it is not working, i only see pulling from http://abc.abc.com/hg/repo.
What should i do for this?

Xcopy in C# - how to call it?

Here I should copy file from nearby local ip address to my local system i have used the following code for copying using the Xcopy command and then launching the process but copying through Argumentsetting in code mentioned if I execute in command prompt it is copying but through code is not copying please tell what is the issue. Any ideas? what through code not copying.
string Porocess = String.Format("\"{0}\\xcopy.exe\"", Environment.SystemDirectory.ToString());
string SolutionSettings = string.Format("\"\\\\{0}\\C$\\Documents and Settings\\All Users\\Application Data\\Symantec\\Common Client\\settings.bak\"", IPaddress);
string TargetSettings = string.Format("\"C:\\Documents and Settings\\All Users\\Application Data\\Symantec\\settings.bak\"");
string Argumentsetting = /*"\"" +*/ SolutionSettings + " " + TargetSettings + " /Y";// parameters to launch process
int iret1 = LauncProcess(Porocess, Argumentsetting, Environment.SystemDirectory.ToString());
public static int LauncProcess(string sProcess, string sParams, string sWorkingDir)
{
int iRet = 0;
Process process = null;
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = sProcess;
startInfo.Arguments = sParams;
startInfo.WorkingDirectory = sWorkingDir;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
process = Process.Start(startInfo);
process.WaitForExit();
Console.WriteLine("Copy has finished.");
if (process.HasExited)
{
Console.WriteLine("Process has exited.");
if (process.ExitCode != 0)
{
iRet = 1;
}
else
{
iRet = 0;
}
}
else
{
iRet = 1;
}
}
catch (Exception ex)
{
iRet = 1;
}
finally
{
process.Dispose();
}
return iRet;
}
check whether source address and destination address are correctly given
Process process = new Process();
process.StartInfo.Arguments= #"D:\sourcePath F:\DestinationPath /e /y /I";
process.Start();

Categories