5
8

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 1 year has passed since last update.

[C#]ファイルに文字列/バイナリデータを読み書きする

Last updated at Posted at 2019-07-08

やりたいこと

文字列やバイナリのデータをファイルに書いたりファイルに読んだりはよくやることだが、その都度適当なコードを書いていたので、一度自分の簡易的な定型文を作っておきたい。

サンプルコード

Program.cs
using System;
using System.IO;
using System.Linq;

namespace ConsoleApp4
{
    class Program
    {
        static string TargetStringFilePath = @"C:\temp\myfile\TargetString.txt";
        static string TargetBinaryFilePath = @"C:\temp\myfile\TargetBinary.txt";

        static void Main(string[] args)
        {
            WriteStringToFile(TargetStringFilePath, "書き込みます。\r\nあいうえお。\r\n");
            Console.WriteLine(ReadStringFromFile(TargetStringFilePath));

            var bin_in = Enumerable.Range(1, 10).Select(x => (byte)x).ToArray();
            WriteBinaryToFile(TargetBinaryFilePath, bin_in);
            var bin_out = ReadBinaryFromFile(TargetBinaryFilePath);

            Console.ReadLine();
        }

        // 文字列をファイルに書き込み
        public static void WriteStringToFile(string path, string data)
        {
            var dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            using (var fs = new FileStream(path, FileMode.Create))
            using (var sw = new StreamWriter(fs))
            {
                sw.Write(data);
            }
        }

        // 文字列をファイルに書き込み2
        public static void WriteStringToFile2(string path, string data)
        {
            var dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            // 簡素なやり方。第二引数をtrueにすると、同じファイルに追記できる)
            using (var sw = new StreamWriter(path, true))
            {
                sw.Write(data);
            }
        }


        // 文字列をファイルから読み込み
        public static string ReadStringFromFile(string path)
        {
            string data = string.Empty;

            if (File.Exists(path))
            {
                using (var fs = new FileStream(path, FileMode.Open))
                using (var sr = new StreamReader(fs))
                {
                    data = sr.ReadToEnd();
#if false
                    // こうすれば、1行ごとにも取り出せる
                    while (sr.Peek() != -1)
                    {
                        Console.WriteLine(sr.ReadLine());
                    }
#endif
                }
            }
            return data;
        }

        // バイナリデータをファイルに書き込み(書き込み先のフォルダがない場合は作成する)
        public static void WriteBinaryToFile(string path, byte[] data)
        {
            var dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            using (var fs = new FileStream(path, FileMode.Create))
            using (var sw = new BinaryWriter(fs))
            {
                sw.Write(data);
            }
        }

        // バイナリデータをファイルから読み込み
        public static byte[] ReadBinaryFromFile(string path)
        {
            if (File.Exists(path))
            {
                using (var fs = new FileStream(path, FileMode.Open))
                using (var sr = new BinaryReader(fs))
                {
                    int len = (int)fs.Length;
                    byte[] data = new byte[len];
                    sr.Read(data, 0, len);

                    return data;
                }
            }

            return null;
        }
    }
}

5
8
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
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?