DEV Community

Kiron Roy
Kiron Roy

Posted on • Updated on

C# Read Text File using Windows Terminal

This is a updated version using Windows Terminal

Here is how to:

  1. write a multi-line text file in Windows Terminal
  2. using Ubuntu (within Windows Terminal)
  3. use Pico text editor (within Windows Terminal) to write and save a sample.txt
  4. read that file in a C# console application

1. open Windows Terminal

Click the "down arrow" and select Ubuntu

type cd Desktop && pico sample.txt

In the pico editor write Windows Terminal is awesome

pressCtrl + o to write out the file

pressCtrl + x to save sample.txt to the Desktop

2. open Visual Studio, here is the code:

Program.cs
using System;

namespace ConsoleUI
{
    class Program
    {
        static void Main(string[] args)
        {
            ReadTextFileIntoConsole readTextFileIntoConsole = new ReadTextFileIntoConsole();
            readTextFileIntoConsole.ReadTextFile();

            Console.ReadLine();

        }

    }
}
Enter fullscreen mode Exit fullscreen mode
ReadTextFileIntoConsole.cs
using System;
using System.IO;

namespace ConsoleUI

{
    public class ReadTextFileIntoConsole
    {
        public void ReadTextFile()
        {
            try
            {
                string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "sample.txt");

                using (StreamReader inputFile = new StreamReader(filePath))
                {
                    Console.WriteLine(inputFile.ReadToEnd());

                }
            }
            catch (Exception e)
            {

                Console.WriteLine("There was an error reading the file: ");
                Console.WriteLine(e.Message);
            }

        }

    }

}
Enter fullscreen mode Exit fullscreen mode

Helpful links (I made a few changes by creating a separate class and method)

Discussion (0)