C# テキストファイルの取得して内容を表示する

  • 作成日 2021.06.14
  • C#
C# テキストファイルの取得して内容を表示する

C#で、StreamReaderを使用して、テキストファイルの取得して内容を表示するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

StreamReader使い方

StreamReaderを使用すると、テキストファイルの取得して内容を表示することが可能です。

StreamReader str = new StreamReader("ファイル名");

以下は、「TextFile1.txt」の内容を取得して表示するサンプルコードとなります。

ソースコード

using System;
using System.IO;
using System.Text;
using System.Linq;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {

            string line;

            StreamReader str = new StreamReader(
                @"C:\Users\testuser\source\repos\testapp\testapp\TextFile1.txt");

            while ((line = str.ReadLine()) != null)
            {
                System.Console.WriteLine(line);
                //hello
                //world
                //!!
            }

            str.Close();

        }
    }
}