Passing data to executable file with PHP - c#

This is my PHP code for passing data to a C# exe file.
<?
shell_exec("p3.exe --tRyMe");
?>
What I want is, I'll post a string to p3.exe file, and that exe file prints "tRyme" string to the screen.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string a;
Console.Write("Please enter a string : ");
a = Console.ReadLine();
Console.WriteLine("You have entered: {0}", a);
Console.ReadKey();
}
}
}
And this is my C# code.
I've tried "--tRyMe", "-tRyMe", "tRyMe" etc. to do that but, this code prints only "Please enter a string" to the screen.
What I want is see the output like:
You have entered: tRyMe
Can you help me with doing that?
Best wishes.

I can't discuss the PHP code, but in the c# side, you need to check the number of arguments passed to your program from the command line and if there is an argument, don't ask for input, but print the argument received
static void Main(string[] args)
{
string a;
if(args.Length == 0)
{
Console.Write("Please enter a string : ");
a = Console.ReadLine();
}
else
a = args[0];
Console.WriteLine("You have entered: {0}", a);
Console.ReadKey();
}

Without having tried it, does a pipe work?
<?php
shell_exec("echo tRyMe | p3.exe");
?>

you could only run an application and print the output but you can not interact with the application - Console.ReadLine() expects an input ...
so you can't use it (affects also Console.ReadKey())
try this:
static void Main(string[] args)
{
string a;
if(args.Length == 0)
a = "No arg is given";
else
a = args[0];
Console.WriteLine("You have entered: {0}", a);
}

Related

Print text on same line as user input using C# Console

I'm trying to use C#'s Console.ReadLine() method to take user input from the console, then subsequently print text on the same line.
Code being used:
using System;
namespace Test {
class Program {
static void Main(string[] args) {
Console.ReadLine();
Console.Write(" out");
}
}
}
What I'm expecting from the console:
in out
What's actually being produced:
in
out
Note that in here is being typed into the console.
Any assistance would be greatly appreciated. Thanks!
-chris
The problem is that it automatically echoes the user input, including the newline when the enter key is pressed. So you have to stop it from echoing the input and handle that yourself.
You can do this by using Console.ReadKey(Boolean) and passing true to intercept the key, and only write it to the output if it's not the enter key.
That would look like this:
using System;
namespace Test {
class Program {
static void Main(string[] args) {
while (true) {
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter) {
break;
} else {
Console.Write(key.KeyChar);
}
}
Console.WriteLine(" out");
}
}
}

C# console application executing code when Console.ReadLine() executes

I'm currently messing around with a Console application and I have some logic to get user input for 3 different things. I have the application designed so that the user can type 'Q' or 'q' at any time to exit the program. However, the way I am currently accomplishing this is through if statements after each user input (using the Console.ReadLine().)
A solution I thought of that would be better is to have a piece of code in one place that exits the program and is called automatically when the ReadLine() is executed and checks the input to see if it is 'q' or 'Q'. I was curious if there was any way to do something like this???
Here is the code I have now
Console.WriteLine("Please give me a source and destination directory...(Enter 'Q' anytime to exit)");
Console.Write("Enter source path: ");
_sourcePath = Console.ReadLine();
if (_sourcePath.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
Console.Write("Enter destination path: ");
_destinationPath = Console.ReadLine();
if (_destinationPath.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
Console.Write("Do you want detailed information displayed during the copy process? ");
string response = Console.ReadLine();
if (response.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
if (response?.Substring(0, 1).ToUpper() == "Y")
{
_detailedReport = true;
}
It would be nice to remove the if blocks and just have the incoming value from the Console.ReadLine() checked when it is executed...
You can create a function to get the user's input and after the Console.ReadLine() just do any processing (exiting on 'q') on the input before returning it.
static void Main(string[] args)
{
Console.Write("Enter source path: ");
var _sourcePath = GetInput();
Console.Write("Enter destination path: ");
var _destinationPath = GetInput();
Console.Write("Do you want detailed information displayed during the copy process? ");
var response = GetInput();
var _detailedReport = response?.Substring(0, 1)
.Equals("y", StringComparison.CurrentCultureIgnoreCase);
}
private static string GetInput()
{
var input = Console.ReadLine();
if (input.Equals("q", StringComparison.CurrentCultureIgnoreCase))
Environment.Exit(Environment.ExitCode);
return input;
}
I'm afraid there's no direct way to hook into the ReadLine() call. Wrapping it all in your own method called 'ReadLine' could work though, say something like
static string ReadLine()
{
string line = Console.ReadLine();
if (line.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
//Other global stuff
return line;
}
//Elsewhere
Console.Write("Enter source path: ");
_sourcePath = ReadLine(); //Note: No 'Console.' beforehand. This is your method!
Console.Write("Enter destination path: ");
_destinationPath = ReadLine();
Console.Write("Do you want detailed information displayed during the copy process? ");
string response = ReadLine();
if (response?.Substring(0, 1).ToUpper() == "Y")
{
_detailedReport = true;
}

How do I use if else statements in c#?

I'm from a python background and I'm finding it difficult to pick up the syntax in c#.
I'm trying to write code so that the program will continuously ask the user for input and it will echo it on the screen, but if the user input is 'exit' then it exits.
I tried
Console.WriteLine("Hello World!");
Console.Write("Enter some text: ");
string userinput = Console.ReadLine();
if (userinput == "exit")
{
Console.ReadKey();
}
else
{
Console.WriteLine(userinput);
But it doesn't achieve expected results
An if statement only executes once.
Since you're looking to take some action repeatedly, a do/while construct is more along the lines of what you need.
Something like this should at least get you started in the right direction:
string userinput;
do
{
Console.Write("Enter some text: ");
userinput = Console.ReadLine();
Console.WriteLine(userinput);
}
while (userinput != "exit");

How to interact with data piped to console application similar to the LESS program [duplicate]

I know how to program Console application with parameters, example : myProgram.exe param1 param2.
My question is, how can I make my program works with |, example : echo "word" | myProgram.exe?
You need to use Console.Read() and Console.ReadLine() as if you were reading user input. Pipes replace user input transparently. You can't use both easily (although I'm sure it's quite possible...).
Edit:
A simple cat style program:
class Program
{
static void Main(string[] args)
{
string s;
while ((s = Console.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
And when run, as expected, the output:
C:\...\ConsoleApplication1\bin\Debug>echo "Foo bar baz" | ConsoleApplication1.exe
"Foo bar baz"
C:\...\ConsoleApplication1\bin\Debug>
The following will not suspend the application for input and works when data is or is not piped. A bit of a hack; and due to the error catching, performance could lack when numerous piped calls are made but... easy.
public static void Main(String[] args)
{
String pipedText = "";
bool isKeyAvailable;
try
{
isKeyAvailable = System.Console.KeyAvailable;
}
catch (InvalidOperationException expected)
{
pipedText = System.Console.In.ReadToEnd();
}
//do something with pipedText or the args
}
in .NET 4.5 it's
if (Console.IsInputRedirected)
{
using(stream s = Console.OpenStandardInput())
{
...
This is the way to do it:
static void Main(string[] args)
{
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192))); // This will allow input >256 chars
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine("Data read was " + input);
}
}
This allows two usage methods. Read from standard input:
C:\test>myProgram.exe
hello
Data read was hello
or read from piped input:
C:\test>echo hello | myProgram.exe
Data read was hello
Here is another alternate solution that was put together from the other solutions plus a peek().
Without the Peek() I was experiencing that the app would not return without ctrl-c at the end when doing "type t.txt | prog.exe" where t.txt is a multi-line file. But just "prog.exe" or "echo hi | prog.exe" worked fine.
this code is meant to only process piped input.
static int Main(string[] args)
{
// if nothing is being piped in, then exit
if (!IsPipedInput())
return 0;
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine(input);
}
return 0;
}
private static bool IsPipedInput()
{
try
{
bool isKey = Console.KeyAvailable;
return false;
}
catch
{
return true;
}
}
This will also work for
c:\MyApp.exe < input.txt
I had to use a StringBuilder to manipulate the inputs captured from Stdin:
public static void Main()
{
List<string> salesLines = new List<string>();
Console.InputEncoding = Encoding.UTF8;
using (StreamReader reader = new StreamReader(Console.OpenStandardInput(), Console.InputEncoding))
{
string stdin;
do
{
StringBuilder stdinBuilder = new StringBuilder();
stdin = reader.ReadLine();
stdinBuilder.Append(stdin);
var lineIn = stdin;
if (stdinBuilder.ToString().Trim() != "")
{
salesLines.Add(stdinBuilder.ToString().Trim());
}
} while (stdin != null);
}
}
Console.In is a reference to a TextReader wrapped around the standard input stream. When piping large amounts of data to your program, it might be easier to work with that way.
there is a problem with supplied example.
while ((s = Console.ReadLine()) != null)
will stuck waiting for input if program was launched without piped data. so user has to manually press any key to exit program.

Console terminates after Console.Read(), even with Console.ReadLine() at the end

The following code asks for your name and surname.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Your name: " + s);
Console.Write("Enter your surname: ");
int r = Console.Read();
Console.WriteLine("Your surname: " + r);
Console.ReadLine();
}
}
After entering the name, the program successfully displays your input. However, after entering a surname, the program stops immediately. From my understanding, Console.Read() should return an int value of the first character of the string I enter (ASCII code?).
Why does the program terminate right after Console.Read()? Shouldn't Console.ReadLine() ensure the program stays open? I am using Visual Studio 2012.
When you tell the console to enter your surname you are asking for a single character.
Console.Write("Enter your surname: ");
int r = Console.Read();
This surely should be a ReadLine followed by another ReadLine before exit. You are probably entering the first character (into Read), followed by subsequent characters, then hitting enter to accept the surname but you are actually on the ReadLine that will exit. So:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Your name: " + s);
Console.Write("Enter your surname: ");
// change here
string surname = Console.ReadLine();
Console.WriteLine("Your surname: " + surname);
Console.ReadLine();
}
}
The program does not terminate after int r = Console.Read() for me.
Based on how the console application was run it will execute all the lines of code and then 'return'. Once done this will close the program as for all intents and purposes it has done what it needs to. It isn't going to sit around and be open when it has finished.
If you want it to keep the window open write Console.Readline() at the end and it will stay open, until some input has been done. I remember having this issue when I started out, and it's not a matter of the program closing unexpectedly, but rather you wanting to see the results in the console before it closes.

Categories