C# Console application read/writes on standard IO doesn't works - c#

Have C# Console application which read/writes on standard input and output.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Console application");
while(true)
{
int input = Console.Read();
Console.WriteLine(input.ToString());
}
}
}
I have other native application which launch above console application and read/writes with help of pipe communication.
C# console application writes are read successfully in external application and also initial writes from external application works fine and then it loops to read from the C# console application.
After that writes from external application on the pipe doesn't work.
Absurd thing is problem is happening on some of the operating system and few it is working fine.
C# Console application compile with .NET Framework 4 / Client Profile.

Known issue from MS :
http://support.microsoft.com/en-us/kb/2675468
Please check the KB for more details along with sample provided.

Try
static void Main(string[] args)
{
Console.SetIn(new StreamReader(Console.OpenStandardInput()));
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine(input);
}
}
Does it work that way?
EDIT: I have updated my answer.
Sample usage/output:
dir /B | ConsoleApplication1.exe
produces:
ConsoleApplication1.exe
ConsoleApplication1.exe.config
ConsoleApplication1.pdb
ConsoleApplication1.vshost.exe
ConsoleApplication1.vshost.exe.config
ConsoleApplication1.vshost.exe.manifest
When I try your original code, it ends up spamming -1 constantly.
You can also try:
while (true)
{
int input = Console.Read();
if (input != -1) { // -1 = no input
Console.WriteLine(input.ToString());
}
}
Now it handles every character separately.

Related

Passing info from one console application to another using Arguments

I am not sure why this does not work. I have two applications one is the main application the second is called upon when needed to perform a task. to simplify I am taking out all the other code as I just need help with this one task
Console Application 1
static void Main()
{
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.FileName = #"C:\ConsoleApp2.application";
startinfo.Arguments = "DateRange ClinetID PhoneNo";
Process.Start(startinfo);
}
Console Application 2
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Received the following arguments:\n" + args.Length);
for (var i = 0; i < args.Length; i++)
{
Console.WriteLine($"[{i}] = {args[i]}");
}
Console.WriteLine("\nPress any key to exit");
Console.ReadLine();
}
}
When I run this code the second application will open fine, however, the args.length is always 0. Any help would be great.
You seem to be in some misunderstanding, are you sure it's not .exe?
Two .Net Framework 4.8 Console Apps were created in the vs 2022 community, which can run correctly as shown in the figure.
If you have questions, please comment below.

C# Pause one console application when other console application starts

I have one console application for testing purposes like following:
static void Main(string[] args)
{
do
{
for (int i = 0; i < 10000000; i++)
{
Console.WriteLine("Doing some endless loop");
Console.WriteLine(i.ToString());
}
} while (true);
}
As you can see the code is very basic, and I've set it up to endless loop in order to test what I would like to achieve.
The other console application is called "Updater" and I would like to to pause the "EndlessLoop" console application once the "Updater" application is started.
Does anyone knows if this is doable in c# .NET?
public static bool IsAppRunning()
{
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName.Contains("Updater"))
{
return true;
}
}
return false;
}
If you call this in while loop it tells you if Updater is running or not.
Not easy to communicate between 2 application
One proposition: When your console Updater starts, you create a file in folder C:\Temps\token.txt. Then, if your console EndlessLoop detects a file names token.txt in C:\Temps, you pause EndlessLoop

How do I stop my C# console program from stopping when executing "console.readline();" twice

i'm really new to C# and i've been working on this really simple command line style program (that has custom commands and such). Now the commands work great but every time I allow the user to go back to enter another command or just anything it closes the program when I press enter. But only the second time I execute a command. I think this has something to do with console.WriteLine();
Here's my code (I've searched everywhere on how to fix this and nothing that i've found has worked)
using System;
namespace ConsoleProgram
{
class Program
{
private static string userEnteredCommand;
static void Main(string[] args)
{
Console.Title = "IAO Systems Service Console";
onCommandLineStart();
void onCommandLineStart()
{
Console.WriteLine("Copyright (C) 2018 IAO Corporation");
Console.WriteLine("IAO Systems Service Console (type 'sinfo' for more information.");
userEnteredCommand = Console.ReadLine();
}
void onCommandLineReturn()
{
userEnteredCommand = Console.ReadLine();
}
// Commands
if (userEnteredCommand == "sinfo")
{
Console.WriteLine(" ");
Console.WriteLine("Program information:");
Console.WriteLine("Created for IAO Corporation, by Zreddx");
Console.WriteLine("This program controls doors, gates and e.t.c within IAO Terratory.");
Console.WriteLine(" ");
Console.WriteLine("This program is protected by copyright, do not redistribute. ");
}
else
{
Console.WriteLine("That command does not exist, do 'programs' for a list of actions.");
}
onCommandLineReturn();
}
}
}
Console applications close when they get to the end of Main. It's exiting after the Console.ReadLine in onCommandLineReturn();.
Add a bool variable called keepLooping, set it to true, and wrap your code in a while(keepLooping) statement. Somewhere in your program flow, check for input like "quit" or "exit" and set the keepLooping variable to false.
Here's an example of it in a dotnetfiddle: https://dotnetfiddle.net/Jguj5k

receive output of Get-Content with wait switch in a console application

I'm trying to process log file output and put it on the plot. However, I can't put my hands around Get-Content -Wait.
It seems that my C# program is not being invoked at all. Works fine without the wait switch, but that's not what I need.
Simple sample:
using static System.Console;
public class Program
{
public static void Main(string[] args)
{
WriteLine("Starting...");
if (IsInputRedirected)
{
while (In.Peek() != -1)
{
Write("[");
var input = In.ReadLine();
WriteLine($"{input}]");
}
WriteLine("... done.");
}
else
{
WriteLine("Nothing");
}
}
}
With the sample calls like:
gc .\Program.cs | .\bin\Debug.ConsoleTest.exe
and
gc .\Program.cs -Wait | .\bin\Debug.ConsoleTest.exe
Does anybody know how to receive the output of Get-Content with -Wait from console application?
Get-content is used to get the content of a file not strip the output of the program u start.
you can use the get-content on the logfile u genarate but know that if u use wait it will be waiting until u kill the procces waiting.
so in a nutshell Get-content -Wait is only used to follow the a log file being written from a other process.
just use .\Program.cs | .\bin\Debug.ConsoleTest.exe and it will wait until exited.
if you want the stdout and the stderror you need a construction like described Here (please note there is a problem using $stdout = $p.StandardOutput.ReadToEnd() ;$stderr = $p.StandardError.ReadToEnd() for big outputs, they deadlock each other)

How do I use command line arguments in my C# console app?

I am writing a url shortener app and I would like to also create a console app with C# to push the URLs to a WCF service which I have also created.
WCF app will shorten the url on this URI;
http://example.com/shorten/http://exaple.com
so what I want is just that.
My console exe file will be sitting inside c:\dev folder and on Windows command line, I would like to do this;
c:\dev>myapp -throw http://example.com
with this method I would like to talk to that service. there is no problem on talking part. But the problem is how can I supply this -throw thing on the command line and get a response and put that response on the command line and supply a method to copy that to the clipboard. Am I asking too much here? :S I don't know.
Could you direct me somewhere that I can find information on that or could u please give me an example code of this?
Thanks.
EDIT :
I have tried the following code;
class Program {
static void Main(string[] args) {
if (args[0] == "-throw") {
System.Windows.Forms.Clipboard.SetDataObject(args[1]);
Console.WriteLine(args[1] + " has been added to clipboard !");
Console.ReadLine();
}
}
}
and I received the following error;
C:\Apps\ArgsTry\ArgsTry\bin\Debug>ArgsTry
-throw man
Unhandled Exception:
System.Threading.ThreadStateException:
Current thread must be set to single
thread apartment (STA) mode before OLE
calls can be made. Ensur e that your
Main function has STAThreadAttribute
marked on it. at
System.Windows.Forms.Clipboard.SetDataObject(Object
data, Boolean copy, In t32 retryTimes,
Int32 retryDelay) at
System.Windows.Forms.Clipboard.SetDataObject(Object
data) at
ArgsTry.Program.Main(String[] args) in
c:\apps\ArgsTry\ArgsTry\Program.cs:
line 14
C:\Apps\ArgsTry\ArgsTry\bin\Debug>
Passing arguments to a console application is easy:
using System;
public class CommandLine
{
public static void Main(string[] args)
{
for(int i = 0; i < args.Length; i++)
{
if( args[i] == "-throw" )
{
// call http client args[i+1] for URL
}
}
}
}
As for the clipboard, see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard.aspx
See the args below, you can use it to read all the values passed when you run your exe file.
static void Main(string[] args) {

Categories