In C#, input and output (I/O) are typically handled through classes in the
System namespace, with Console being a popular class for console applications. Here’s an overview of how to work with both input and output in C#.1. Console Input
For console-based applications, input is usually taken from the user through the Console.ReadLine and Console.ReadKey methods.
Console.ReadLine(): Reads an entire line of text entered by the user and returns it as a string. It's often used for accepting various types of data from the user, like strings, numbers (which can then be parsed), etc.Console.ReadKey(): Reads a single character from the input without waiting for the Enter key. It returns aConsoleKeyInfoobject that includes the character entered.- // Reading a line of input
- Console.WriteLine("Enter your name:");
- string name = Console.ReadLine();
- Console.WriteLine("Hello, " + name + "!");
- // Reading a single key press
- Console.WriteLine("Press any key to continue...");
- ConsoleKeyInfo keyInfo = Console.ReadKey();
- Console.WriteLine("\nYou pressed: " + keyInfo.KeyChar);
2. Console Output
Console output is mainly done using
Console.WriteandConsole.WriteLinemethods.Console.WriteLine(): Writes a line of text to the console and moves the cursor to the next line.Console.Write(): Similar toWriteLine, but it does not add a newline character, so it continues writing on the same line.- // Simple text output
- Console.WriteLine("Welcome to the program!");
- // Output without a newline
- Console.Write("Loading");
- for (int i = 0; i < 3; i++) {
- Thread.Sleep(500); // Simulates a delay
- Console.Write(".");
- }
- Console.WriteLine("\nDone!");
3. File Input and Output
To read from and write to files, you can use classes in the
System.IOnamespace, such asFile,StreamReader, andStreamWriter.- Reading a file: Use
File.ReadAllText()to read all content at once, orStreamReaderto read line-by-line. - Writing to a file: Use
File.WriteAllText()to write text all at once, orStreamWriterfor line-by-line writing. - using System.IO;
- // Writing to a file
- string path = "example.txt";
- File.WriteAllText(path, "Hello, World!");
- // Reading from a file
- string content = File.ReadAllText(path);
- Console.WriteLine("File Content: " + content);
4. Parsing Input Data
When receiving input, especially from
Console.ReadLine, you may need to convert (or parse) it into the appropriate data type, such as an integer, double, etc., using methods likeint.Parse,double.Parse, orConvert.ToInt32.Console.WriteLine("Enter a number:");
string input = Console.ReadLine();
int number;
if (int.TryParse(input, out number)) {
Console.WriteLine("You entered the number: " + number);
} else {
Console.WriteLine("Invalid input, please enter a number.");
}
- Reading a file: Use

love it, Grecian 😍
ReplyDeleteperfect 🤩
ReplyDeleteAmazing
ReplyDelete