I was writing this code and noticed that the Console.ReadLine() command doesn't wait for input. Those lines are being executed for sure but for some reason the console just closes on me without being able to type.
The class is set to be console application.
public void Register()
{
Console.WriteLine("Enter User Name to Register:");
String nickname = Console.ReadLine();
User newUser = new User(nickname); //todo: check if it doesn't already exist//
this.userList.Add(newUser);
persistantLayer.Saver.saveUser(newUser);
}
Related
I'm doing a TCP Messenger Programm ATM with TCPClient and TCPListener. Everything is working fine. I've had both of these in separate programs and now I'm basically trying to make it one Program. I'm stuck with the fact that it is always WAITING till I have something written to send it before it goes to checking the receive. I'm new to C# and learning. So I need a way to check "is something written? If no, then skip this" basically a bool to ask if something is written.
I've tried to make it like "if the line in storage right now is the same as the was the last time, skip it" so it doesnt stuck infinitly in the Send sector of the program. But still it ALWAYS waits until I wrote something before it even checks/ skips it.
This is the write and send loop code:
nachricht = Console.ReadLine();
if (nachrichtcheck != nachricht)
{
Console.WriteLine("test1");
TcpClient clientnachricht = new TcpClient(zielip, port);
NetworkStream streamnachricht = clientnachricht.GetStream();
sendnachricht = Encoding.ASCII.GetBytes(nachricht);
streamnachricht.Write(sendnachricht, 0, sendnachricht.Length);
streamnachricht.Close();
clientnachricht.Close();
nachrichtcheck = nachricht;
Console.WriteLine("test2");
}
else
{
if (empfangstream.CanRead)
{
Console.WriteLine("test3");
byte[] receivedBuffer2 = new byte[100];
NetworkStream stream = empfangclient.GetStream();
stream.Read(receivedBuffer, 0, receivedBuffer.Length);
StringBuilder msg2 = new StringBuilder();
foreach (byte b in receivedBuffer)
{
if (b.Equals(00))
{
break;
}
else
msg2.Append(Convert.ToChar(b).ToString());
}
Console.WriteLine("test4");
empfangscheck2 = msg2.ToString();
if (empfangscheck2 != empfangscheck)
{
Console.WriteLine(msg2.ToString());
empfangscheck = msg2.ToString();
Console.WriteLine("receive");
}
}
}
So if someone can help me just getting a way to get a bool to check if something is written -> then use it. Except of wait until something is written -> use it it would help me miles.
I've got an alternative to solve your problem. You can use a thread to wait for an user input instead of your actual code.
(I've also considered your german language)
Code Example:
using System;
using System.Threading;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string nachricht = "";
double AndereTätigkeitBeweis = 0;
Thread NachrichtenEinleser = new Thread(()=> {
Console.Write("Gib diene zu sendende Nachricht ein: ");//Type in the message you'd like to send
nachricht = Console.ReadLine();//Read the user Input without stopping the actual code because it's another process
});
NachrichtenEinleser.Start();
//do somewhat activity until you get a user input
while (nachricht == ""){
AndereTätigkeitBeweis++;
}
//Write out the user input
Console.WriteLine($"User Input: {nachricht}|AndereTätigkeitBeweis: {AndereTätigkeitBeweis}");
Console.ReadLine();
}
}
}
Output example:
Gib diene zu sendende Nachricht ein: hallo
User Input: hallo|AndereTätigkeitBeweis: 560075647
Hope this helps.
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
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
I am writing a class that encapsulates a state machine that represents my applications attempts to communicate with my own web service. Basic states are disconnected, connecting, connected, and requiring credentials. I thought for good learning experience about using Rx to publish state changes with a BehaviorSubject (hopefully this in itself is good usage?). One of my states for this subject is the 'Requiring Credentials' where I need to prompt the user to provide a username and password before continuing. For the purposes of this exercise let us assume that the class is hosted in a Windows Console Application and that I want to prompt the user with
Console.WriteLine("Enter username");
var userName = Console.ReadLine();
Console.WriteLine("Enter password");
var password = Console.ReadLine();
As a result of my Rx BehaviorSubject hitting the state 'RequiresCredentials' and it should hit this every time this state is hit.
I have exposed the BehaviorSubject as itself (i.e. haven't hidden it behind an Observable interface or anything)
public BehaviorSubject<ConnectionState> State { get; }
and want this request for credentials to be blocking.
What process should I use for subscribing to this subject correctly, waiting for this input and finally returning control back to the calling thread?
If you're not using tasks or await, or anything asynchronous, Rx subscription code will observe on the same thread, and block if you're using blocking code. If you don't care about the input, then you can do a straight Subscribe. If you want to use the inputted username/password, then you can use Select. So this would work:
class Program
{
static void Main(string[] args)
{
var subject = new BehaviorSubject<ConnectionState>(ConnectionState.Disconnected);
var getCredentials = subject.Where(cs => cs == ConnectionState.RequiresCredentials)
.Select(cs =>
{
Console.WriteLine("Enter username");
var userName = Console.ReadLine();
Console.WriteLine("Enter password");
var password = Console.ReadLine();
return Tuple.Create(userName, password);
});
using (var subscription = getCredentials.Subscribe())
{
Console.WriteLine("Changing to Connecting...");
subject.OnNext(ConnectionState.Connecting);
Console.WriteLine("Changing to RequiresCredentials...");
subject.OnNext(ConnectionState.RequiresCredentials);
Console.WriteLine("Connected.");
subject.OnNext(ConnectionState.Connected);
}
}
}
enum ConnectionState
{
Disconnected,
Connected,
Connecting,
RequiresCredentials
}
It produces the following output:
Changing to Connecting...
Changing to RequiresCredentials...
Enter username
ThisIsMyUserName
Enter password
ThisIsMyPassword
Connected.
This is a rather backwards use of Rx though: If you're looking to use Rx in an iterative, procedural way, why don't you just use C# and save yourself complexity?
Hi there and thanking in advance
I am trying (very hard) to redirect Console input and output into a textbox. So far output is working fine but the trouble is with input.
For example I cannot execute a simple program that will do the following:
Console.WriteLine("Please enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hi there " + name);
The reason I can't achieve this is because that the program has to stop while waiting for user to type his/her name and press enter. If I wait for user input on a new thread then the main GUI thread freezes and the textbox can never receive the KeyPress. This thing has me totally stumped. Any advice (or better still code) would be greatly appreciated.
Cheers
The code below is a Console app that calls another console app to do some work and not a WinForm app, but you could easily replace the event handlers (TransformProcessOutputDataReceived, and TransformProcessErrorDataReceived) to output to a text box instead of a TextWriter. Unfortunately it doesn't directly address your issue of the called console application waiting for user input. The code below does pump some input to the called console app via standard input, so perhaps you could supply it from your windows app in the same manner.
Hope this was helpful, I had a heck of a time getting it to work originally myself, sorry I forgot the original references I had used, it was a while ago.
private static void ProcessRetrievedFiles(List<string> retrievedFiles)
{
Console.WriteLine();
Console.WriteLine("Processing retrieved files:");
Console.WriteLine("---------------------------");
Console.WriteLine();
foreach (string filePath in retrievedFiles)
{
if (String.IsNullOrEmpty(filePath)) continue;
Console.WriteLine(filePath);
Process transformProcess = new Process();
string baseOutputFilePath = Path.Combine(ExportDirectory, Path.GetFileNameWithoutExtension(filePath));
transformProcess.StartInfo.FileName = TransformerExecutablePath;
transformProcess.StartInfo.Arguments = string.Format(
"-i:\"{0}\" -x:\"{1}\" -o:\"{2}.final.xml\"",
filePath,
string.Empty,
baseOutputFilePath);
transformProcess.StartInfo.UseShellExecute = false;
transformProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
transformProcess.StartInfo.RedirectStandardError = true;
transformProcess.StartInfo.RedirectStandardOutput = true;
transformProcess.StartInfo.RedirectStandardInput = true;
transformProcess.EnableRaisingEvents = true;
//attach the error/output recievers for logging purposes
transformProcess.ErrorDataReceived += TransformProcessErrorDataReceived;
transformProcess.OutputDataReceived += TransformProcessOutputDataReceived;
ProcessBridgeFileOutputWriter = new StreamWriter(
baseOutputFilePath + ".log",
false);
ProcessBridgeFileOutputWriter.AutoFlush = true;
transformProcess.Start();
transformProcess.BeginOutputReadLine();
transformProcess.BeginErrorReadLine();
//the exe asks the user to press a key when they are done...
transformProcess.StandardInput.Write(Environment.NewLine);
transformProcess.StandardInput.Flush();
//because we are not doing this asynchronously due to output writer
//complexities we don't want to deal with at this point, we need to
//wait for the process to complete
transformProcess.WaitForExit();
ProcessBridgeFileOutputWriter.Close();
ProcessBridgeFileOutputWriter.Dispose();
//detach the error/output recievers
transformProcess.ErrorDataReceived -= TransformProcessErrorDataReceived;
transformProcess.OutputDataReceived -= TransformProcessOutputDataReceived;
}
}
static void TransformProcessOutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
{
ProcessBridgeFileOutputWriter.WriteLine(e.Data);
}
}
static void TransformProcessErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
{
ProcessBridgeFileOutputWriter.WriteLine(string.Format("ERROR: {0}", e.Data));
}
}