DEV Community

Kiron Roy
Kiron Roy

Posted on • Updated on

C# Read Text File

Here is how to:

  1. write a multi-line text file in powershell
  2. save that file to a text file (.txt)
  3. add more lines to that file
  4. read that file in a C# console application

1. open powershell and type in the following:

PS C:\Users\yourdir\ cd Desktop
PS C:\Users\yourdir\Desktop> $csharp = "C#"
PS C:\Users\yourdir\Desktop> $powershell = "We will learn a little bit about C# and powershell"
PS C:\Users\yourdir\Desktop> $TextOut = @"
>> $csharp
>> $powershell
>> "@
PS C:\Users\yourdir\Desktop> $TextOut >> textstuff.txt
PS C:\Users\yourdir\Desktop> $moretext = "Add some more content" | Add-Content 'textstuff.txt'
Enter fullscreen mode Exit fullscreen mode

Here is a photo from my laptop:

I added some more text:


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), "textstuff.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 (1)

Collapse
vikasjk profile image
Vikas-jk

Good article, If anyone stumbles upon this and want to see more example of how to read text file line by line etc, check:
qawithexperts.com/article/c-sharp/...
thanks