0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

テキストファイル読み書き(C#)

Posted at

概要

いつもいつもファイル操作を忘れるのでメモ

  • 読み込みにはStreamReader、書き込みにはStreamWriterを使う
  • Closeし忘れを防ぐため、usingステートメントを使う

読み込み

ファイルが存在しない場合は"System.IO.FileNotFoundException"がスローされる。

// インスタンス生成
StreamReader reader = new StreamReader(<ファイルパス>);

// エンコーディング指定(Shift_JISを指定する場合)
StreamReader reader = new StreamReader(<ファイルパス>, Encoding.GetEncoding("Shift_JIS"));

テキストファイルの内容をコンソール出力するサンプル

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TextFileReadSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // "TextFile1.txt"を開く
            using (StreamReader reader = new StreamReader("TextFile1.txt"))
            {
                string line;

                // ファイル末尾まで繰り返す
                while(!reader.EndOfStream)
                {
                    // ファイルから1行read
                    line = reader.ReadLine();

                    Console.WriteLine(line);
                }
            }
        }
    }
}

書き込み

ファイルが存在しない場合は作成される。

// インスタンス生成
StreamWriter writer = new StreamWriter(<ファイルパス>);

// エンコーディング指定(Shift_JISを指定する場合)
StreamWriter writer = new StreamWriter(<ファイルパス>, Encoding.GetEncoding("Shift_JIS"));

文字列をファイルに書き込み、その内容をコンソール出力するサンプル

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TextFileWriteSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // "TextFile2.txt" を開く
            using (StreamWriter writer = new StreamWriter("TextFile2.txt"))
            {
                // 文字列を書き込む
                writer.WriteLine("TextFileWriteSample");
            }


            // 書き込んだファイルを開いて内容をコンソール出力する
            using (StreamReader reader = new StreamReader("TextFile2.txt"))
            {
                string line;

                while (!reader.EndOfStream)
                {
                    line = reader.ReadLine();
                    Console.WriteLine(line);
                }
            }
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?