Multiple IFs won't work - c#

I'm creating a Desktop application (console) for Windows, using C#.
This is my code:
namespace myapp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello!");
Console.WriteLine("Type 'exit' to exit!");
string line = Console.ReadLine();
if (line == "exit") {
Environment.Exit(0);
}
if (line == "copyright") {
Console.WriteLine("Copyright 2017 TIVJ-dev");
}
}
}
}
If I type "exit", it works fine (I'm sure it does this Environment.Exit(0); action). But if I type "copyright", it does not work. I can see an empty line instead. I started with C# today, so my apologies if this is very beginner problem. I haven't found solution on the internet.
Screenshot:

I'm not sure in what way it doesn't work. It should run
Console.WriteLine("Copyright 2017 TIVJ-dev");
then immediately close the console window. Try putting another
Console.ReadLine();
at the end of Main().

You could use an else if statement;
namespace myapp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello!");
Console.WriteLine("Type 'exit' to exit!");
string line = Console.ReadLine();
if (line == "exit")
{
Environment.Exit(0);
}
else if (line == "copyright") {
Console.WriteLine("Copyright 2017 TIVJ-dev");
}
}
}
}
Edit
By using an if/else this does the same as using multiple if statements however this is a more efficient way and make it easier when using break points.

Try launching the application by pressing ctrl F5 in visual studio and seeing if it works. Alternatively click on debug->start without debugging.
Then write "copyright" and press enter.
What is probably happening is that the console is printing the line, then closing before you have a chance to see it. When you don't use the debugger the console stays open even once the application is finished.

Now everyone: Now this project works fine! Thanks for people who said add another Console.ReadLine. When I tested else if, I forgot there was that also. But now it works, so I try to close this. Thanks everyone!

Related

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

The program '[11476] ConsoleApp22.exe' has exited with code 0 (0x0)

using System;
// Namespace
namespace ConsoleApp22
{
// Main Class
class Program
{
// Entry Point Method
static void Main(string[] args)
{
string name = "Florent Shomora";
// start here
Console.Write("Hello World"+ name);
}
}
}
This is my code and the problem is that the console pop up and die.
Do you want to see console window ? Try to use Console.Readline()
static void Main(string[] args)
{
string name = "Florent Shomora";
// start here
Console.Write("Hello World"+ name);
Console.Readline();
}
The problem is that your program works without error.
However, what does your program do? It prints a message to the screen, nothing more. This is a very fast operation. The program will complete this operation and terminate probably faster than you can read the message.
You can pause the program by adding another operation which will take more time, such as expecting user input:
string name = "Florent Shomora";
// start here
Console.Write("Hello World"+ name);
Console.ReadLine();
With that extra call to ReadLine() the application will now remain open and wait for you to press "return" before closing.
Try
Console.Readline()
it should show u the Console and u can exit by clicking for example enter

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

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.

Console.ReadLine() skips the first input character

Console.WriteLine("You have not installed Microsoft SQL Server 2008 R2, do you want to install it now? (Y/N): ");
//var answerKey = Console.ReadKey();
//var answer = answerKey.Key;
var answer = Console.ReadLine();
Console.WriteLine("After key pressed.");
Console.WriteLine("Before checking the pressed key.");
//if(answer == ConsoleKey.N || answer != ConsoleKey.Y)
if (string.IsNullOrEmpty(answer) || string.IsNullOrEmpty(answer.Trim()) || string.Compare(answer.Trim(), "N", true) == 0)
{
Console.WriteLine("The installation can not proceed.");
Console.Read();
return;
}
I have tried to input these:
y -> it gives me an empty string,
y(whitespace+y) -> it gives me the "y"
I have checked other similar posts, but none of them solves my problem.
The ReadLine() still skips the 1st input character.
UPDATE Solved, see below.
Suggested change:
Console.Write("Enter some text: ");
String response = Console.ReadLine();
Console.WriteLine("You entered: " + response + ".");
Key points:
1) A string is probably the easiest type of console input to handle
2) Console input is line oriented - you must type "Enter" before the input becomes available to the program.
Thank you all for replying my post.
It's my bad that not taking consideration of the multi-thread feature in my code. I will try to explain where I was wrong in order to say thank you to all your replies.
BackgroundWorker worker = .....;
public static void Main(string[] args)
{
InitWorker();
Console.Read();
}
public static void InitWorker()
{
....
worker.RunWorkerAsync();
}
static void worker_DoWork(....)
{
.....this is where I wrote the code...
}
The problem was I started a sub-thread which runs asynchronously with the host thread. When the sub-thread ran to this line : var answer = Console.ReadLine();
the host thread ran to the Console.Read(); at the same time.
So what happened was it looked like I was inputting a character for var answer = Console.ReadLine();, but it actually fed to the Console.Read() which was running on the host thread and then it's the turn for the sub-thread to ReadLine(). When the sub-thread got the input from keyboard, the 1st inputted character had already been taken by the host thread and then the whole program finished and closed.
I hope my explanation is clear.
Basically you need to change Console.Read --> Console.ReadLine

Categories