execute multi-line cmd command in c# - c#

I am creating java compiler in c# .it is working perfect if there is no input.but it ask forstrong text input it give me error (Exception in thread "main" java.util.NoSuchElementException: No line found)
public void executeit()
{
adresss = "";
string dir = textBox1.Text;
adresss = dir;
ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
info.CreateNoWindow = true;
string[] s = new string[30];
s = Directory.GetDirectories(#"C:\Program Files\Java\", "jdk1*");
info.WorkingDirectory = s[0] + #"\bin\";
info.Arguments = "/c javac " + "\"" + dir + "\"";
Process p = new Process();
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
label1.Text = "";
p.StartInfo = info;
p.Start();
StreamReader sw = p.StandardError;
string err = sw.ReadToEnd();
label1.Text = err;
if (label1.Text == "")
{
label1.Text = "Compiled without Errors";
}
}
and it is java file:
import java.util.Scanner;
public class inputtry {
public static void main (String args[]){
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
//get user input for a
String a=reader.nextLine();
System.out.print("number is:");
System.out.print(a);
}
}

Related

Rename host name via c#

I am trying to rename my computer name programmatically via C#. I have added the admin credentials and password in my code. While running the same I'm getting return value as 5 which is access denied. But when I'm running the exe file as admin and providing the credentials in UAC, system name is getting renamed.
What can be the problem in code or what can be enhancement in this.
My code is below
class Program
{
static string systemSrNo = string.Empty;
static string Hostname = string.Empty;
static string NewHostName = string.Empty;
static ManagementObjectSearcher MOS;
static string domain = "WORKGROUP";
static string username = "Admin";
static string pass = "MTIz";
static System.Security.SecureString EncryptPWD;
static string Outputline = string.Empty;
static string Outputline1 = string.Empty;
static StreamReader errorReader;
static void Main(string[] args)
{
systemSrNo = "CurrentSerialNumber";
Hostname = "CurrentHostName";
NewHostName = "NewHostName";
string renameHostOP = RenameHostName(Hostname, NewHostName);
}
private static string RenameHostName(string Hostname, string newName)
{
try
{
ProcessStartInfo procStartInfo = new ProcessStartInfo();
Process p = new Process();
var encodedTextBytes = Convert.FromBase64String(pass);
string domainpwdD = System.Text.Encoding.UTF8.GetString(encodedTextBytes);
System.Security.SecureString pwd = new System.Security.SecureString();
string Password = domainpwdD;
foreach (char c in Password)
pwd.AppendChar(c);
procStartInfo.CreateNoWindow = true;
procStartInfo.FileName = #"WMIC.exe";
procStartInfo.Verb = "runas";
procStartInfo.WindowStyle = ProcessWindowStyle.Maximized;
procStartInfo.UserName = username;
procStartInfo.Password = pwd;
procStartInfo.Domain = "workgroup";
procStartInfo.UseShellExecute = false;
procStartInfo.Arguments = "computersystem where caption='" + Hostname + "' rename '" + newName + "'";
procStartInfo.RedirectStandardError = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.RedirectStandardOutput = true;
p.StartInfo = procStartInfo;
try
{
p.Start();
}
catch (Exception e)
{
Console.WriteLine("exception" + e);
}
StreamReader outputWriter = p.StandardOutput;
errorReader = p.StandardError;
Outputline = outputWriter.ReadLine();
while (!(outputWriter.EndOfStream))
{
Outputline += outputWriter.ReadLine();
}
Console.WriteLine("a: " + Outputline);
p.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine(" Exception occured while Renaming HostName: " + ex.Message);
}
finally
{
Console.WriteLine(" Renaming Hostname completed");
}
return Outputline;
}
}
Error :
Executing (\CurrentHostName\ROOT\CIMV2:Win32_ComputerSystem.Name="CurrentHostName")->rename()Method execution successful.Out Parameters:instance of __PARAMETERS{ ReturnValue = 5;};

C# is unable to create a process and call a R script by that process

My c# code
public static string RunRScript(string filePath, string rScriptExecutablePath, string args, int totalFiles,
int RowsInChunk, int TotalRows, string identity)
{
string rCodeFilePath = filePath; //RScriptPath.GetFilePath();
//string file = rCodeFilePath;
string result = string.Empty;
// IEnumerable<string> connections = _connections.GetConnections(identity)
try
{
var info = new ProcessStartInfo();
info.FileName = rScriptExecutablePath;
info.WorkingDirectory = Path.GetDirectoryName(rScriptExecutablePath);
info.Arguments = "\"" + rCodeFilePath + "\"" + " " + args;
info.RedirectStandardInput = false;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;
string fileName = string.Empty;
DateTime startTime = DateTime.Now;
List<ProgressTracker> lstProgress = new List<ProgressTracker>();
ProgressTracker p;
using (var proc = new Process())
{
//proc.StartInfo.Verb = "runas";
for (int i = 1; i <= totalFiles; i++)
{
p = new ProgressTracker();
p.DT = DateTime.Now;
p.Progress = i;
lstProgress.Add(p);
info.Arguments = "\"" + rCodeFilePath + "\"" + " " + args + " " + i.ToString();
proc.StartInfo = info;
proc.Start();
proc.WaitForExit();
result = proc.StandardOutput.ReadToEnd();
p.TimeTaken = (DateTime.Now - p.DT).TotalSeconds;
Functions.SendProgress("Process in progress...", i, totalFiles, RowsInChunk, TotalRows, lstProgress, identity);
}
}
return FormatOutput(result);
}
catch (Exception ex)
{
throw new Exception("R Script failed: " + result, ex);
}
}
Now objects have values like
info.FileName = C:\Program Files\R\R-3.4.3\bin\Rscript.exe
info.WorkingDirectory = C:\Program Files\R\R-3.4.3\bin
info.Arguments = "C:\MANOJ R\Topic modelling v2\TM_Webapi\Honeywell.UOP.TopicModel.Api\Uploads\h481821\TopicSearch.R" h481821 1
But process is not creating and its not calling R script and even it doesn't throwing any exception
Even I tried running VS as admin but no luck!
I have changed the .exe file path from
C:\Program Files\R\R-3.4.3\bin\Rscript.exe
to
C:\Program Files\R\R-3.4.3\bin\x64\Rscript.exe
Since I am using 64 bit machine
Now the process is working

Process.Start cannot run batch file properly

I am trying to run a batch file using C#
The batch file for the test purposes contains
msg * Test
It works if I run it manually.
Then I use the following code to run this .bat file
filePath = full path to batch file
var startInfo = new ProcessStartInfo
{
Arguments = "/C \"" + filePath + "\"",
FileName = "cmd.exe",
UseShellExecute = true
};
Process p = Process.Start(startInfo);
and it does not work ->
cannot find msg
What I am doing wrong?
P.S. the batch file should not be changed.
Try this way:
batchfile:
set "msg=%SystemRoot%\System32\msg.exe"
if not exist "%msg%" set "msg=%SystemRoot%\Sysnative\msg.exe"
"%msg%" * Hello
code:
string sFile = <full path to batch file>;
Process.Start("cmd.exe", "/c " + sFile);
Probably need some authorization, you may try the following code:
static void ExecuteCommand(string command)
{
int exitCode;
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.Domain = "domain"; // Your own domain
processInfo.UserName = "userName"; // Your own user name
System.Security.SecureString s = new System.Security.SecureString();
s.AppendChar('p'); // Your own password
s.AppendChar('a');
s.AppendChar('s');
s.AppendChar('s');
s.AppendChar('w');
s.AppendChar('o');
s.AppendChar('r');
s.AppendChar('d');
processInfo.Password = s;
processInfo.UseShellExecute = false;
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
process = Process.Start(processInfo);
process.WaitForExit();
// *** Read the streams ***
// Warning: This approach can lead to deadlocks, see Edit #2
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
exitCode = process.ExitCode;
Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" :
output));
Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" :
error));
Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
process.Close();
}
static void Main()
{
ExecuteCommand(#"C:\displayMsg.bat");
}
You may check your domain in Control Panel >> User Account >> Manage User Accounts
Source of reference: source
The problem is the location of the file (msg.exe) in the different OS versions (32bit/64bit)
I suppose it helps How can I execute msg.exe by C# in windows?
Edited:
It works fine -
class Program
{
static void Main(string[] args)
{
int ExitCode;
try
{
var returnedMsgPath = string.Empty;
if (LocateMsgExe(out returnedMsgPath))
{
var startInfo = new ProcessStartInfo()
{
FileName = returnedMsgPath,
Arguments = #"* /v Hello",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true
};
var p = Process.Start(startInfo);
p.WaitForExit();
// *** Read the streams ***
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
ExitCode = p.ExitCode;
MessageBox.Show("output >>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
p.Close();
}
else
{
MessageBox.Show("Not found");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static bool LocateMsgExe(out string returnedMsgPath)
{
returnedMsgPath = null;
string[] msgPaths = new string[] { Environment.ExpandEnvironmentVariables(#"%windir%\system32\msg.exe"),
Environment.ExpandEnvironmentVariables(#"%windir%\sysnative\msg.exe") };
foreach (string msgPath in msgPaths)
{
if (File.Exists(msgPath))
{
returnedMsgPath = msgPath;
return true;
}
}
return false;
}
}

C# ProcessStartInfo Print Copies To Printer

I want to be able to print multiple copies set from the printer dialogue and send them to the printer.
using (System.Windows.Forms.PrintDialog printerDialog = new System.Windows.Forms.PrintDialog())
{
string printer;
if (printerDialog.ShowDialog() == DialogResult.OK)
{
printer = printerDialog.PrinterSettings.PrinterName;
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(GetDocPath("StickerBlank.docx", Client.ClientID.ToString()));
for (int i = 0; i < printerDialog.PrinterSettings.Copies; i++)
{
Thread.Sleep(3000);
using (var regWord = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Winword.exe"))
{
//string arguments = String.Format(#"-t ""{0}"" ""{1}""", printerDialo, printer);
if (regWord == null)
{
info.Arguments = "\"" + printer + "\"";
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.UseShellExecute = true;
info.Verb = "Print";
}
else
{
info.Arguments = "\"" + printer + "\"";
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.UseShellExecute = true;
info.Verb = "PrintTo";
}
}
System.Diagnostics.Process.Start(info);
}
}
}
It works but the problem is that the word document which is my template opens as much as copies are set from the printdialog. Is there a way to specify that i want 5 copies as arguments?

C# how can I run cygwin scp and put in password using Process and StandardInputWriter?

With this code I see the login window prompting for a password but I can't seem to write the password to the shell window.
Process scp = new Process();
scp.StartInfo.FileName = #"c:\cygwin\bin\scp";
scp.StartInfo.Arguments = "/cygdrive/c" + path + " " + username + "#" + ServerName + ":/cygdrive/c/Temp/.";
scp.StartInfo.UseShellExecute = false;
scp.StartInfo.RedirectStandardOutput = true;
scp.StartInfo.RedirectStandardError = true;
scp.StartInfo.RedirectStandardInput = true;
scp.Start();
//I've tried this with no success:
using (StreamWriter sw = scp.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine(pass);
}
}
// Another failed attempt:
scp.StandardInput.Write(pass + Environment.NewLine);
scp.StandardInput.Flush();
Thread.Sleep(1000);
I know I can get this to work with cygwin expect but would rather use c# to interact with the windows input / output.
Try this:
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
Process scp = new Process();
scp.StartInfo.FileName = #"c:\cygwin\bin\scp";
scp.StartInfo.Arguments = "/cygdrive/c" + path + " " + username + "#" + ServerName + ":/cygdrive/c/Temp/.";
scp.StartInfo.UseShellExecute = false;
scp.StartInfo.RedirectStandardOutput = true;
scp.StartInfo.RedirectStandardError = true;
scp.StartInfo.RedirectStandardInput = true;
scp.Start();
Process[] p = Process.GetProcessesByName("cmd");
SetForegroundWindow(p[0].MainWindowHandle);
SendKeys.SendWait(pass);
scp.WaitForExit();
EDIT: Be sure to include \n at the end of pass.
this code works fine as expected and with no need to call Flush or Sleep:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("dir");
}
}
are you 100% sure that your cygwin is just waiting for the pwd?

Categories

Resources