LoginSignup
0
1

More than 3 years have passed since last update.

ファイルの読み書き

Posted at

はじめに

ただの備忘用のメモです。
ファイルの入出力ってたまに使うんですが何故か思い出せないことが多いです (´-ω-`)

環境

Microsoft Visual Studio Community 2019 Version 16.4.3
.NET Core 3.1

書く、読む

FileStream, StreamWriter, StreamReader を使います。
オーバーロードがいろいろあるんですがその中から目についたモノを書いておきます。
※詳細は[参考]を参照

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

namespace ConsoleApp7
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // ファイルパスを渡すと内部でFileStreamが生成されてそこにデータが流し込まれる
            // StreamWriterにMemoryStreamとかを渡せば書き込み先を変えられる
            using (var writer = new StreamWriter(@".\test.txt", append: true, encoding: Encoding.UTF8))
            {
                writer.WriteLine("hogeee");

                // 非同期でも書ける
                await writer.WriteLineAsync("hunngaaa!!");
            }

            using (var stream = new FileStream(@".\test.bin", FileMode.Append, FileAccess.Write))
            {
                stream.Write(new byte[] { 0x66, 0x32, 0x87, 0x12, 0x11, 0x88, 0x45, 0x23 });

                // バイナリの場合も非同期で書ける
                await stream.WriteAsync(new byte[] { 0x76, 0x12, 0x23, 0x99, 0x50, 0x43, 0x18, 0x66 });
            }


            // StreamWriterと同じ要領で使える
            using (var reader = new StreamReader(@".\test.txt", Encoding.UTF8))
            {
                Console.WriteLine(reader.ReadLine());
                Console.WriteLine(await reader.ReadLineAsync());
            }

            // あんまり使わない
            using (var stream = new FileStream(@".\test.bin", FileMode.Open, FileAccess.Read))
            {
                var buffer = new byte[8];
                stream.Read(buffer, 0, 8);
                Console.WriteLine(string.Join(", ", buffer.Select(b => $"{b,2:x2}")));

                await stream.ReadAsync(buffer, 0, 8);
                Console.WriteLine(string.Join(", ", buffer.Select(b => $"{b,2:x2}")));
            }
        }
    }
}

参考

FileStream クラス
StreamWriter クラス
StreamReader クラス
$ - 文字列補間
複合書式指定

0
1
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
1