計算機科学のブログ

reading and writing files - System IO, StreamWriter, File, WriteLine method, Close method

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 10(reading and writing files - Save the last byte for me!)、p.535(StreamWriter Magnets)の解答を求めてみる。

コード

Flobbo.cs

using System.IO;
namespace MyConsoleApp
{
    internal class Flobbo
    {
        private string zap;
        public Flobbo(string zap)
        {
            this.zap = zap;
        }
        public StreamWriter Snobbo()
        {
            return new StreamWriter("macaw.txt");
        }
        public bool Blobbo(StreamWriter sw)
        {
            sw.WriteLine(zap);
            zap = "green purple";
            return false;
        }
        public bool Blobbo(bool already, StreamWriter sw)
        {
            if (already)
            {
                sw.WriteLine(zap);
                sw.Close();
                return false;
            }
            else
            {
                sw.WriteLine(zap);
                zap = "red orange";
                return true;
            }
        }
    }
}

入出力結果(Terminal, Zsh)

% cat ~/Projects/MyConsoleApp/MyConsoleApp/bin/Debug/net5.0/macaw.txt
blue yellow
green purple
red orange
%