LoginSignup
4
5

More than 5 years have passed since last update.

Macで.NET Coreのプログラムでファイルの読み書きをしてみる

Posted at

Macで.NETのプログラムを書いてみるの続き。

ファイルを読み込んでみる

StreamReaderの罠にハマる

「C#でファイルの読み書き」くらいのキーワードで検索して、さっそくコードを描いてみる。

using System;
using System.IO;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
          string filename = "input.txt";
            using (StreamReader sr = new StreamReader(filename))
            {
                while(sr.Peek() >0){
                    String line = sr.ReadLine();
                    Console.WriteLine(line);
                }
            }
        }
    }
}

簡単だ。実に分かりやすい。ファイルをStreamReaderで開いて、ReadLine()メソッドで行単位で読みだす。

ところが、これは、フルの.NET Frameworkでは動作するのだけれど、.NET Core環境では動作しない。

エラーメッセージによると、 /Program.cs(11,55): error CS1503: Argument 1: cannot convert from 'string' to 'System.IO.Stream' とのことで、StreamReader sr = new StreamReader(filename)というのがイカンらしい。

修正版

エラーメッセージを見れば分かるように、StreamReaderのコンストラクターに渡す引数として、string型の文字列でファイルパスを渡すのは間違っているらしい。
ここには、Streamを渡す必要があるようだ。というワケで、FileStreamを渡す。
new StreamReader(new FileStream(filename, FileMode.Open)))

というワケで、修正した。

using System;
using System.IO;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string filename = "input.txt";
            using (StreamReader sr = new StreamReader(new FileStream(filename, FileMode.Open)))
            {
                while(sr.Peek() >0){
                    String line = sr.ReadLine();
                    Console.WriteLine(line);
                }
            }
        }
    }
}

これで、buildすればOK。

Compiling hello for .NETCoreApp,Version=v1.1
Compilation succeeded.
    0 Warning(s)
    0 Error(s)
Time elapsed 00:00:03.0119207

(私にとって)意外なハマりポイントだったので、メモっておいた。

4
5
2

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