C# Console.ReadLine() never reads input on VSC in Linux - c#

I've got a Console.ReadLine() inside a finite for loop that never ends reading.
I am using VS Code on Linux Mint. I execute by pressing F5.
using System;
class Person
{
public string Name { get; set;}
public override string ToString()
{
return "My name is " + Name;
}
}
class Program
{
static void Main(string[] args)
{
int n = 3;
Person[] p = new Person[n];
for (int i = 0; i < n; i++)
{
p[i] = new Person()
{
Name = Console.ReadLine()
};
Console.WriteLine("I just read " + p[i]);
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(p[i].ToString());
}
}
}
I expected to input three names and then output them.
I input by typing a name and then pressing Enter.
The issue is that I can keep inputting forever and that Console.WriteLine("I just read " + p[i]); never gets executed. This happens in the Debug Console.

I can't reproduce this on Windows or Ubuntu. My guess is that Mint buffers the output.
Try adding Console.Out.Flush(); after Console.WriteLine("I just read " + p[i]);

This is still an issue on Linux. Running Visual Studio Code, in debug mode. Output is being directed to Debug Console, but input is not being considered.
It only works when running from command line, but that basically disallows for debugging.
Though the answer for this problem is here
Debug Console window cannot accept Console.ReadLine() input during debugging

Related

Can't input data with Console.ReadLine

I'm trainning in C# alone for this moment, and encounter my first problem.
I use VSCode as IDE.
What I Am Try To Do
Create two functions, the first, data like name and return it. the second return full name. All in one in a class.
What I Do From Here
using System
namespace Helloworld
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine(p.getFullName())
}
public string getName(string message)
{
string? name;
do
{
Console.WriteLine(message);
name = Console.ReadLine();
}
while (string.IsNullOrEmpty(firstName)); // For avoid null or empty string, I'm not found another solution.
return name;
}
public string getFullName()
{
const string firstNameMessage = "Enter your first name: ";
const string lastNameMessage = "Enter yout last name: ";
string result = $"{getName(firstNameMessage)} {getName(lastNameMessage)}"
return result;
}
}
}
I Have Encountered Any Problems
1 - When I launch the command dotnet run, my program follow instructions while the first Console.WriteLine. When I type an random name in VSCode's Debug Console. Nothing happens...
My questions: Does this problem come my code ? Am I using an unsuitable IDE ? Or Am I not working with the good VSCode's Tools ?
2 - When I want restart or build I have a message like The process cannot access the file C:\Users\Username\ Documents\Work\learningCSharp\bin\Debug\net6.0\learningCSharp.dll' because it is being used by another process.
My question: How I kill process which use my DLL file ?
I solve all my problem finally alone. I read here the solution.
I'm posting the solution anyway.
in your launch.json replace "console": "internalConsole" by "console": "integratedTerminal.
If you are senior in C#, Can you tell us if is it same for all IDEs ?

WPF Application Standard Output Overwrite Line

I've a WPF Application that I can launch with command line in a PowerShell like this :
MyProgram.exe -arg1 -arg2 | Out-Default
I need to write in this PowerShell a progress bar that overwrite itself at each step. There is my code :
public void PerformNextState()
{
++mStep;
double nbRectangleToCompleteTheBar = 100.0;
string prefix = "\r0% [";
string suffix = "] 100%";
StringBuilder str = new StringBuilder();
str.Append(prefix);
int nbRectangles = (int)Math.Round(nbRectangleToCompleteTheBar * mStep / mMaxItems);
int i = 0;
for (; i < nbRectangles; ++i)
{
str.Append('█');
}
for (; i < nbRectangleToCompleteTheBar; ++i)
{
str.Append(' ');
}
str.Append(suffix);
Console.Write(str.ToString());
}
But the carriage return seems interpreted like a new line :
As you can see the character █ is also misinterpreted.
I also tried with this syntax \x000D instead \r with the same results.
Furthermore, I tried to do it with Console.SetCursorPosition(), Console.CursorLeft and Console.CursorTop but I get IOException probably because it's a WPF Application and not Console Application.
I tried all these solutions in a Console Application and they all work.
And I don't want to compile my WPF Application as Console Application because I think it's not a good practice and I will need to hide the console when launched with GUI.

C#: 'System.IO.FileNotFoundException' and 'Debug profile does not exist'

EDIT: It turns out that the local variable was not the issue. Even after changing it I get the error message from Visual Studio Community (was using VS code before):
"An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module. Could not load file or assembly 'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
If I create a new project, and copy and paste the code, a different message appears:
The debug executable 'D:\Desktop\New folder\ConsoleApp1\ConsoleApp1\bin\Debug\netcoreapp3.1\ConsoleApp1.exe' specified in the 'ConsoleApp1' debug profile does not exist
A problem also appears saying the program does not contain a Static Main, but the previous replies say the code works as it is.
OLD:
At college we have done a C# exercise (code will be further down) that for some reason does not work on my computer, despite being exactly the same (I have even copy and pasted someone else's that did work on theirs but not on mine). The code was meant to accept a number from the user and see if it was within a range or not, and depending on that output a message.
For some reason, it appears that a local variable is not being read as it shows up as the wrong color, but if you hover the mouse over the word, a pop-up menu does say it is a local variable. The variable is the 'result' after the 'if' and before the brackets (line 15).
At first we thought it was a problem with Visual Studio Code, so I tried it on Visual Studio Community 2019 and it still did not work. I already have the relevant framework. My teachers think there is a problem with my device, what do you think?
Here is how it looks in VS code
Here is the pop-up menu that appears
Here are the list of problems after debugging
And here is the source code:
using System;
namespace Csharp_learning
{
class MainDemo
{
static int ReadNumber(string prompt, int min, int max)
{
int result = 0;
do
{
Console.Write(prompt);
string numberString = Console.ReadLine();
result = int.Parse(numberString);
if result (result > max || result < min)
Console.WriteLine("Please enter a value in the range " + min + " to " + max);
else
break;
}
while(true);
return result;
}
}
}
This is my first time using this website, sorry if I did not present this correctly.
using System;
namespace Csharp_learning
{
class MainDemo
{
public static int ReadNumber(string prompt, int min, int max)
{
int result = 0;
do
{
Console.Write(prompt);
string numberString = Console.ReadLine();
result = int.Parse(numberString);
if (result > max || result < min)
Console.WriteLine("Please enter a value in the range " + min + " to " + max);
else
break;
}
while (true);
return result;
}
}
}
You have an extra result before if statement.
As for the other error you can try the link below.
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module
A problem also appears saying the program does not contain a Static Main, but the previous replies say the code works as it is.
Every c# console program has a static main. I was under the impression you already knew that. That part should look a little like below.
using System;
namespace Csharp_learning
{
class Program
{
static void Main(string[] args)
{
MainDemo.ReadNumber("Prompt input ", 1, 10);
}
}
}
These two different code blocks are most often in different files but you could just try copying in below to see if it works.
using System;
namespace Csharp_learning
{
class MainDemo
{
public static int ReadNumber(string prompt, int min, int max)
{
int result = 0;
do
{
Console.Write(prompt);
string numberString = Console.ReadLine();
result = int.Parse(numberString);
if (result > max || result < min)
Console.WriteLine("Please enter a value in the range " + min + " to " + max);
else
break;
}
while (true);
return result;
}
}
}
namespace Csharp_learning
{
class Program
{
static void Main(string[] args)
{
MainDemo.ReadNumber("Prompt input ", 1, 10);
}
}
}
Your code runs fine for me. It works as expected. The error suggest there is a typo in the project file. Open your CSharp Learning.csproj project file and look for parenthesis that are mismatched or out of place. Another solution would be to create a new project. Then copy your code the the new project.

"The process cannot access the file because it is being used by another process." with SystemReader

I have no coding experience but have been trying to fix a broken program many years ago. I've been fumbling through fixing things but have stumbled upon a piece that I can't fix. From what I've gathered you get Alexa to append a Dropbox file and the program reads that file looking for the change and, depending on what it is, executes a certain command based on a customizable list in an XML document.
I've gotten this to work about five times in the hundred of attempts I've done, every other time it will crash and Visual Studio gives me: "System.IO.IOException: 'The process cannot access the file 'C:\Users\\"User"\Dropbox\controlcomputer\controlfile.txt' because it is being used by another process.'"
This is the file that Dropbox appends and this only happens when I append the file, otherwise, the program works fine and I can navigate it.
I believe this is the code that handles this as this is the only mention of StreamReader in all of the code:
public static void launchTaskControlFile(string path)
{
int num = 0;
StreamReader streamReader = new StreamReader(path);
string str = "";
while (true)
{
string str1 = streamReader.ReadLine();
string str2 = str1;
if (str1 == null)
{
break;
}
str = str2.TrimStart(new char[] { '#' });
num++;
}
streamReader.Close();
if (str.Contains("Google"))
{
MainWindow.googleSearch(str);
}
else if (str.Contains("LockDown") && Settings.Default.lockdownEnabled)
{
MainWindow.executeLock();
}
else if (str.Contains("Shutdown") && Settings.Default.shutdownEnabled)
{
MainWindow.executeShutdown();
}
else if (str.Contains("Restart") && Settings.Default.restartEnabled)
{
MainWindow.executeRestart();
}
else if (!str.Contains("Password"))
{
MainWindow.launchApplication(str);
}
else
{
SendKeys.SendWait(" ");
Thread.Sleep(500);
string str3 = "potato";
for (int i = 0; i < str3.Length; i++)
{
SendKeys.SendWait(str3[i].ToString());
}
}
Console.ReadLine();
}
I've searched online but have no idea how I could apply anything I've found to this. Once again before working on this I have no coding experience so act like you're talking to a toddler.
Sorry if anything I added here is unnecessary I'm just trying to be thorough. Any help would be appreciated.
I set up a try delay pattern like Adriano Repetti said and it seems to be working, however doing that flat out would only cause it to not crash so I had to add a loop around it and set the loop to stop when a variable hit 1, which happened whenever any command types are triggered. This takes it out of the loop and sets the integer back to 0, triggering the loop again. That seems to be working now.

Why does the console close after my last input?

My program allows the user to put in 20 prices and to display the average of those values. Why does the console close after I enter my last input? Below is the code I'm running:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace machineproblem4
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
double average = 0;
Console.WriteLine("\t\t\t INPUT PRICES \n");
int[] price = new int[20];
Console.WriteLine("\t\t\t Please enter 20 prices \n");
for (int ctr = 0; ctr < 20; ctr++)
{
Console.Write("Enter price {0} : ", ctr + 1);
price[ctr] = Convert.ToInt32(Console.ReadLine());
}
// [...calculate sum...]
//average
Console.WriteLine("\n----------------------------");
Console.WriteLine("||average of the prices||");
average = sum / 20;
Console.WriteLine("average of the prices: {0}", average);
//more code that outputs statistics about the inputs
//exit
//Edit: This is what fixed my problem
Console.WriteLine("press any key to exit ..");
Console.ReadKey();
}
}
}
use Console.Readline();
Read(), ReadLine() and ReadKey() are basically static methods, and they comes under the Console class. That's why we use these methods like:
Console.Read():-- method accept the String and return the integer.
Console.ReadLine():--method accept the String and return string .
Console.ReadKey():--method accept the Character and also return Character.
That's why we mostly use the Console.ReadKey() method, for come back to source code from output window .
Because when we only press the character we directly come on source code. If you will use the Console.Read() and Console.ReadLine method then
you need to press Enter, come back to the source code rather then any character.
You can place a Console.Read() at the last statement. You can also place a breakpoint at your last statement
Generally, it is not a good idea to wait for user input from a console application. This is okay for debugging, but not definitely for release.
So, first find out if your application is in debug or release config using
private static bool IsDebug()
{
object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(DebuggableAttribute), false);
if ((customAttributes != null) && (customAttributes.Length == 1))
{
DebuggableAttribute attribute = customAttributes[0] as DebuggableAttribute;
return (attribute.IsJITOptimizerDisabled && attribute.IsJITTrackingEnabled);
}
return false;
}
Then use,
if (IsDebug())
Console.Readline();
This eliminates the need to edit the code for different build configurations. Alternative is to put a breakpoint and debug the console app, as suggested by #Erwin
Put:
Console.Readline();
at the end of your main function, so it waits until you press enter before it closes.
None of the previous answers actually directly answer the question of why this is happening. The reason why the console is closing after your last input is that the rest of the code runs very quickly and when it reaches the end of your program, the console closes. This is correct behavior and should be expected when running a console application. As the other answers have stated, you can work around this by requiring a final input before closing the console, but that is all it is, a work around.
If you were to output to a text file rather than just the console, you would see that all of the output is generated as you would expect. The console output and close is just too fast for you to see it without some sort of pause in the code.
Additionally, a solution that has not been mentioned yet is to run the project from Visual Studio without debugging, which will automatically output "Press any key to continue..." when it finishes processing before closing the console. That way you can see what it is outputting without extraneous code that you wouldn't want to have in production code.

Categories

Resources