Console I/O
Now, we are going to play with console input output.
First, we need to get our file location in a folder.
var fileName = Path.Combine(directory.FullName, "data.txt");
Now, we want to get the text in our file. Then, we should write our data.txt with"Hello, Makers".
Our class will be like this. new FileInfo(fileName)
is to check our data inside our file. Then, we have to make sure whether the file is exist or not.
class Program
{
static void Main(string[] args)
{
string currentDirectory = Directory.GetCurrentDirectory();
DirectoryInfo directory = new DirectoryInfo(currentDirectory);
var fileName = Path.Combine(directory.FullName, "data.txt");
var file = new FileInfo(fileName);
if (file.Exists)
{
}
}
}
Inside our if condition, we try to read the file.
if (file.Exists)
{
using (var reader = new StreamReader(file.FullName))
{
Console.SetIn(reader);
Console.WriteLine(Console.ReadLine());
}
}
Basically, we need to close the file that we opened before. Fortunately, using
method helps us to do that automatically.
StreamReader
is to open the file.
Console.SetIn
is to set an input for console.
Console.WriteLine(Console.ReadLine())
means the console will read what already SetIn and write it to console.